java - 具有标识符的 Hibernate 可嵌入列表映射

标签 java hibernate jpa annotations hibernate-mapping

我有一个带有可嵌入地址的 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/

相关文章:

java - 如何将mockito与maven测试工具一起使用

java - OpenJPA 不规则地抛出 EntityExistsException

java - JNI C函数无法解析android串口Api

java - 如何对内部使用 HttpURLConnection 的类进行单元测试?

java - 尝试在 Activator UI 中运行 Pay Java Seed 时缺少依赖项 'object java.lang.Object in compiler mirror'

java - org.hibernate.exception.ConstraintViolationException : could not execute statement

hibernate - 如何在Grails中更改 map 的映射

mysql - 使用 ONLY_FULL_GROUP_BY mysql 模式 hibernate

java - EJB 无法更新数据模型

sql - 无法级联删除@OneToOne 成员