How to make a one-to-many bidirectional relationship with JPA annotations owned by its collection

I have a mapping in XML from Hibernate docs. My question is how to do this with JPA annotations. This is a one-to-many bidirectional relationship, and the assembled side belongs to it. Thank.

<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>

      

+3


source to share


1 answer


In the case where the collection is the owning side, you need to make it @ManyToOne

non-isolated and non-recoverable by removing mappedBy

from the side @OneToMany

:

@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;
}

      



This mapping should generate a link table, but if you want to override it, use the annotation as well @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;
}

      

+3


source







All Articles