Hibernate Mapping - Joining two tables with an association table - But with a twist

前端 未结 2 1323
执念已碎
执念已碎 2021-01-24 16:15

I have the following entities... Customer, Card and Address

Customer:

 {
     private String cust_id; // Primary k         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-24 16:22

    You could use the annotation @JoinTable after the @OneToOne to point the card's table, so you won't need an entity for card, but if the card's table isn't just a relational table, you could map card in User as @OneToOne and have a @Transient 'getAddress()' method that returns 'this.card.getAddress()', but on card's entity you must map the relation between Address and Card(@OneToOne(mappedBy='card_id')), and in Address you could map card_id as @Id.

    First Alternative

    Customer:

    @OneToOne
    @JoinTable(name="card", joinColumns = @JoinColumn(name="cust_id"),
    inverseJoinColumns = @JoinColumn(name="card_id"))
    private Address address;
    

    Second alternative

    Customer:

    @OneToOne(mappedBy="cust_id")
    private Card card;
    
    ...
    @Transient
    public Address getAddress(){
     return this.card == null ? null : this.card.getAddress();
    }
    

    Card:

    @OneToOne(mappedBy="card_id")
    private Address address;
    

    Address:

    @Id
    private String card_id;
    

    In the Second case Card has a Embedded pk which is formed by two fks(Customer and Address)

    Card:

    @EmbeddedId
    private CustomerAddressPK id;
    

    CustomerAddressPK

    @Embeddable
    public class CustomerAddressPK(){
    
      private String cust_id;
      private String card_id;
    }
    

提交回复
热议问题