在使用@OneToMany的情况下,不能将主键直接嵌入子实体中,而是应该使用外键来关联父子实体。以下是示例代码:
// 父实体 @Entity public class Parent { @Id private Long id;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "parent")
private Set children;
}
// 子实体 @Entity public class Child { @EmbeddedId private ChildId id;
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("parentId")
private Parent parent;
//其他属性
}
//复合ID @Embeddable public class ChildId implements Serializable{ private Long parentId; private Long childId;
//getter方法
}
//保存实体 Parent parent = new Parent(); Child child = new Child(); ChildId childId = new ChildId(); childId.setParentId(parent.getId()); child.setId(childId); child.setParent(parent); parent.getChildren().add(child); session.save(parent);
在这个例子中,我们使用复合主键作为嵌入式ID对象,并将其关联到子实体中的@ManyToOne查询。这样,在保存父实体时,Hibernate将为子实体保存外键。