JAVA如何通过uuid获取主键,如何使用UUID作为Hibernate实体的主键?

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.

解决方案

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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值