使用compositeKey的Hibernate示例OneToMany
您能否举例说明以下情况的Hibernate映射:
- 父表(
foo
)带有一个简单的主键(foo_id
) -
子表(
bar
),由复合键组成a)父表的外键(
foo_id
)b)字符串类型的键(
item
) - 许多孩子有一个父母
- Parent类将具有Child对象的列表
- 保存,更新,删除父类时,更改将级联到子级
我没有完全按照你要求做的事情,但这可能会让你朝着正确的方向前进。 我认为它应该工作。 本页更详细地解释了这些注释。
@Entity public class Foo { @Id @GeneratedValue(strategy=GenerationType.AUTO) public Long getId(){ } ... @OneToMany(mappedBy="foo") public Collection getBars() { } ... } @Entity @IdClass(BarPk.class) public class Bar implements Serializable { @ManyToOne @JoinColumn(name="foo") @Id public Foo getFoo() { return foo; } @Column(name="key", length=255) @Id public String getKey(){ } } @Embeddable public class BarPk implements Serializable { public Foo getFoo() { return foo; } public void setFoo(Foo foo) { } public String getKey(){ ... } public void setKey(String key){ ... } //you must include equals() and hashcode() }
是的,您应该使用以下映射
@Entity public class Parent {
@Id private Integer id; @CollectionOfElements @JoinTable( name="Child", joinColumn=@JoinColumn(name="PARENT_ID")) @IndexColumn("childIndex") private List childList = new ArrayList ();
}
注意@CollectionOfElements和IndexColumn是Hibernate特定的注释,而不是JPA 1.0规范。 JPA 2.0将介绍它们。
@Embeddable public class Child {
// @Embeddable class does not contains identifiers // child class specific property's
}
所以下面的代码将正常工作
Parent parent = new Parent();
parent.getChildList()。add(new Child()); parent.getChildList()。add(new Child()); //其他孩子
session.save(父); //将保存父母和两个孩子
此问题的缺点是@CollectionOfElements注释仅适用于@Embeddadble类,而不适用于Entity类。 如果您想将Child类作为Entity类,我希望看到解决方案。 不可能同时将@Entity和@Embeddable注释应用于类。
关心Arthur Ronald FD Garcia(Java程序员)Natal / RN – 巴西
- Maven – 如何为hibernate添加所有必需的依赖项?
- 在Hibernate中使用saveOrUpdate()创建新记录而不是更新现有记录
- Hibernate 3.6.10不会通过OneToMany JoinTable级联删除
- Java持久性:转换为Query.getResultList()的结果?
- 正则表达式疯狂:java.util.regex.Pattern matcher进入高CPU循环
- Spring + JPA +多个持久性单元:注入EntityManager
- 使用Hibernate中的注释定义默认列值
- 使用Hibernate将Oracle Date映射到Java对象
- Criteria API返回的结果集太小