我有一个带有可嵌入地址的 Person 实体,它们之间存在一对多关系(一个人可以有多个地址)。当前的映射是这样的:
@Embeddable
public class Address {
// ... attributes
}
@Entity
public class Person {
@ElementCollection(fetch = FetchType.EAGER)
@JoinTable(name = "Person_addresses", joinColumns = @JoinColumn(name = "personid")
)
/*
Attribute ovverrides with annotations
*/
private java.util.Set<Address> addresses = new java.util.HashSet<Address>();
}
使用此注释意味着在数据库中我有一个 Person_addresses 表,其中包含所有地址属性和一个 personid。但这也意味着如果我有一个地址列表的人并且我更新了地址列表,Hibernate 会删除所有相关记录并再次插入它们(修改后的记录)。
据我所知,有一种方法可以在该表中为每条记录设置一个主键——在这种情况下,hibernate 可以决定列表中的哪一项需要更新。所以我的问题是,如何在连接表中映射带有标识符的可嵌入列表? (我希望我想要的是可以理解的:))。
最佳答案
http://en.wikibooks.org/wiki/Java_Persistence/ElementCollection#Primary_keys_in_CollectionTable
The JPA 2.0 specification does not provide a way to define the Id in the Embeddable. However, to delete or update a element of the ElementCollection mapping, some unique key is normally required. Otherwise, on every update the JPA provider would need to delete everything from the CollectionTable for the Entity, and then insert the values back. So, the JPA provider will most likely assume that the combination of all of the fields in the Embeddable are unique, in combination with the foreign key (JoinColumn(s)). This however could be inefficient, or just not feasible if the Embeddable is big, or complex. Some JPA providers may allow the Id to be specified in the Embeddable, to resolve this issue. Note in this case the Id only needs to be unique for the collection, not the table, as the foreign key is included. Some may also allow the unique option on the CollectionTable to be used for this. Otherwise, if your Embeddable is complex, you may consider making it an Entity and use a OneToMany instead.
原来如此,做不到。
关于java - 具有标识符的 Hibernate 可嵌入列表映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22508604/