编程语言
首页 > 编程语言> > java-如何与JPA批注建立一对多的双向关系,其中收藏方拥有它

java-如何与JPA批注建立一对多的双向关系,其中收藏方拥有它

作者:互联网

我从Hibernate文档中获得了XML映射.我的问题是如何使用JPA注释.它是一对多的双向关系,而收藏方拥有它.谢谢.

<class name="Person">
    <id name="id" column="personId">
        <generator class="native"/>
    </id>
    <set name="addresses" 
        table="PersonAddress">
        <key column="personId"/>
        <many-to-many column="addressId"
            unique="true"
            class="Address"/>
    </set>
</class>

<class name="Address">
    <id name="id" column="addressId">
        <generator class="native"/>
    </id>
    <join table="PersonAddress" 
        inverse="true" 
        optional="true">
        <key column="addressId"/>
        <many-to-one name="person"
            column="personId"
            not-null="true"/>
    </join>
</class>

解决方法:

对于集合为拥有方的情况,您需要使@ManyToOne不可插入且不可更新,同时在@OneToMany一侧删除mapedBy:

@Entity
@Table(name = "PERSON")
public class Person {

    @Id
    @Column(name = "personId")
    private long id;

    @OneToMany
    private Set<Address> addresses;
}


@Entity
@Table(name = "ADDRESS") 
public class Address {

   @Id
   @Column(name = "addressId")  
   private long id;       

   @ManyToOne
   @JoinColumn(name = "personId", insertable = false, updatable = false)
   private Person person;
}

此映射应生成一个链接表,但是如果要覆盖它,则也可以使用@JoinTable批注:

@Entity
@Table(name = "PERSON")
public class Person {

    @Id
    @Column(name = "personId")
    private long id;

    @OneToMany
    @JoinTable(name="PersonAddress", 
        joinColumns=@JoinColumn(name="personId"),
        inverseJoinColumns=@JoinColumn(name="addressId")
    )
    private Set<Address> addresses;
}


@Entity
@Table(name = "ADDRESS") 
public class Address {

   @Id
   @Column(name = "addressId")  
   private long id;       

   @ManyToOne
   @JoinTable(name="PersonAddress", 
        joinColumns=@JoinColumn(name="addressId", insertable = false, updatable = false),
        inverseJoinColumns=@JoinColumn(name="personId", insertable = false, updatable = false)
   )
   private Person person;
}

标签:orm,jpa,hibernate,hibernate-mapping,java
来源: https://codeday.me/bug/20191120/2047580.html