Hibernate Join two unrelated table when both has Composite Primary Key

前端 未结 5 1572
自闭症患者
自闭症患者 2020-12-31 09:21

I\'m writing java application using hibernate 5.2 but without HQL

there is two table, Transactions and ResponseCode

5条回答
  •  Happy的楠姐
    2020-12-31 10:25

    Your mapping of both entities is wrong.

    Let's start with the ResponseCode entity. Your table model shows a composite primary key that consists of the RcCode and Lang columns. But your entity mapping only declares the rcCode attribute as the primary key. You need to add an additional @Id annotation to the rcLang attribute of the ResponseCode entity.

    This should be the fixed mapping of the ResponseCode entity:

    @Entity
    @Table(name = "response_codes")
    public class ResponseCode implements java.io.Serializable {
        private static final long serialVersionUID = 1L;
    
        @Id
        @Column(name = "response_code")
        private String rcCode;
    
        @Column(name = "rc_status")
        private String rcStatus;
    
        @Column(name = "rc_description")
        private String rcDesc;
    
        @Id
        @Column(name = "rc_lang")
        private String rcLang;
    
        // Contructors and getters/setters
    }
    

    After fixing the primary key of your ReponseCode entity, you need to reference both attributes/columns in the association mapping of your Transaction entity. With Hibernate 5.2, you can do that with 2 of Hibernate's @JoinColumn annotations. Older Hibernate versions and the JPA standard in version 2.1 need to wrap these annotations in an additional @JoinColumns annotation.

    Here is the fixed mapping of your Transaction entity:

    @Entity
    @Table(name = "transactions")
    public class Transaction implements java.io.Serializable {
        private static final long serialVersionUID = 1L;
    
        @Column(name = "merchant_id", nullable = true)
        private String merchantID;
    
        @Column(name = "tran_amount", nullable = true)
        private String tranAmount;
    
        @Id
        @Column(name = "tran_type", nullable = true)
        private String tranType;
    
        @Column(name = "auth_request_date", nullable = true)
        @Temporal(TemporalType.TIMESTAMP)
        private Date authRequestDate;
    
        @Id
        @Column(name = "tran_id", nullable = true)
        private String tranID;
    
        @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
        @JoinColumn(name="rc_id", referencedColumnName = "id")
        @JoinColumn(name="rc_lang", referencedColumnName = "lang")
        private ResponseCode rc;
    
        // Contructos and getters/setters
    

提交回复
热议问题