How to use UUID as primary key for Hibernate Entity?

ⅰ亾dé卋堺 提交于 2019-12-10 11:35:44

问题


I am trying to use UUID in Hibernate.

Have the following @Entity base-class description (with @MappedSuperclass annotation):

 @Id
 @Column(name="id")
 private UUID id;

 public UUID getId()
 {
  return id;
 }

For test, I am trying to read all entities of my class from database (database exists, records exist). My database is PostgreSQL 8.4 with UUID support and primary key is of UUID type.

Running my test I get the following in log:

[junit] 14:21:34,839  INFO LongType:203 - could not read column value from result set: id0_0_; Bad value for type long : d46668b8-e494-42ba-803f-c43524ac3f31

...

[junit] org.postgresql.util.PSQLException: Bad value for type long : d46668b8-e494-42ba-803f-c43524ac3f31
[junit]     at org.postgresql.jdbc2.AbstractJdbc2ResultSet.toLong(AbstractJdbc2ResultSet.java:2796)
[junit]     at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getLong(AbstractJdbc2ResultSet.java:2019)
[junit]     at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getLong(AbstractJdbc2ResultSet.java:2431)
[junit]     at org.apache.commons.dbcp.DelegatingResultSet.getLong(DelegatingResultSet.java:240)
[junit]     at org.hibernate.type.LongType.get(LongType.java:51)
[junit]     at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:184)
[junit]     at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:173)
[junit]     at org.hibernate.loader.Loader.getKeyFromResultSet(Loader.java:1121)

Looks like Hibernate doesn't really use UUID type it may parse from my entity annotated description. The same situation with Spring instead of UUID.

How else I can tell Hibernate I would like to user either UUID or String instead of Long for primary key?

PS: Hibernate I use 3.3.2.GA. I don't use EntityManager. I describe mapping with annotations and configure Hibernate with Spring.


回答1:


I would typify the key as String:

private UUID id;

@Id
@Column(name="id")
public String getId()
{
    return id.toString();
}

public void setId(String value)
{
    id = UUID.fromString(value);
}

public UUID idAsUUID()
{
    return id;
}


来源:https://stackoverflow.com/questions/3254707/how-to-use-uuid-as-primary-key-for-hibernate-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!