can someone please explain me @MapsId in hibernate?

后端 未结 5 1671
天涯浪人
天涯浪人 2020-11-29 03:34

Can someone please explain to me @MapsId in hibernate? I\'m having a hard time understanding it.

It would be great if one could explain it with an examp

5条回答
  •  被撕碎了的回忆
    2020-11-29 03:54

    IMHO, the best way to think about @MapsId is when you need to map a composite key in a n:m entity.

    For instance, a customer can have one or more consultant and a consultant can have one or more customer:

    And your entites would be something like this (pseudo Java code):

    @Entity
    public class Customer {
       @Id
       private Integer id;
    
       private String name;
    }
    
    @Entity
    public class Consultant {
       @Id
       private Integer id;
    
       private String name;
    
       @OneToMany
       private List customerByConsultants = new ArrayList<>();
    
       public void add(CustomerByConsultant cbc) {
          cbc.setConsultant(this);
          this.customerByConsultant.add(cbc);
       }
    }
    
    @Embeddable
    public class ConsultantByConsultantPk implements Serializable {
    
        private Integer customerId;
    
        private Integer consultantId;
    }
    
    @Entity
    public class ConsultantByConsultant {
    
       @EmbeddedId
       private ConsultantByConsultantPk id = new ConsultantByConsultantPk();
    
       @MapsId("customerId")
       @JoinColumn(insertable = false, updatable = false)
       Customer customer;
    
       @MapsId("consultantId")
       @JoinColumn(insertable = false, updatable = false)
       Consultant consultant;
    }
    

    Mapping this way, JPA automagically inserts Customer and Consultant ids in the EmbeddableId whenever you save a consultant. So you don't need to manually create the ConsultantByConsultantPk.

提交回复
热议问题