Hibernate注解: 联合主键:@IdClass vs @EmbeddedId

本文介绍Hibernate中实现复合主键的三种方法:使用@Embeddable和@Id、使用@EmbeddedId以及使用@IdClass,并强调了主键类需要实现Serializable接口及重写equals()和hashCode()方法的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Hibernate Annotations -> 2.2.6. Mapping composite primary keys and foreign keys to composite primary keys:
[url]http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e2177[/url][quote][size=small]Composite primary keys use a embedded class as the primary key representation, so [b]you'd use the @Id and @Embeddable annotations. Alternatively, you can use the @EmbeddedId annotation. [color=red]Note that the dependent class has to be serializable and implements equals()/hashCode()[/color][/b]. You can also use @IdClass.[/size]
@Entity
public class RegionalArticle implements Serializable {

@Id
public RegionalArticlePk getPk() { ... }
}

@Embeddable
public class RegionalArticlePk implements Serializable { ... }
or alternatively
@Entity
public class RegionalArticle implements Serializable {

@EmbeddedId
public RegionalArticlePk getPk() { ... }
}

public class RegionalArticlePk implements Serializable { ... }

与这段摘录呼应的一篇文章:
[url]http://blog.youkuaiyun.com/zzh87615/article/details/6083754[/url][quote]hibernate的annotation的文档中提供了三种方法
  1 将组件类注解为@Embeddable,并将组件的属性注解为@Id
  2 将组件的属性注解为@EmbeddedId (方便)
  3 将类注解为@IdClass,并将该实体中所有属于主键的属性都注解为@Id(符合编程习惯)
主键类需要序列化(考虑到可能会将数据读写到虚拟内存中),需要重写hashcode()和equals()方法,因为要对联合主键进行比较.[/quote][/quote]


Hibernate Annotation 联合主键三种写法的例子:
[b][url]http://laodaobazi.iteye.com/blog/903236[/url][/b]


Which anotation should I use: @IdClass or @EmbeddedId:
[url]http://stackoverflow.com/questions/212350/which-anotation-should-i-use-idclass-or-embeddedid[/url]

Compound Primary Keys with Hibernate and JPA Annotations:
[url]http://jpa.ezhibernate.com/Javacode/learn.jsp?tutorial=15usingcompoundprimarykeys[/url]

@IdClass and @EmbeddedId:
[url]http://www.coderanch.com/t/452567/ORM/java/IdClass-EmbeddedId[/url]


遇到的一个bug:使用IdClass,居然不认@Column:
[url]https://hibernate.onjira.com//browse/HHH-4256[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值