2015-06-19 108 views
0

我得到了這個問題,這是一個非常常見的問題,我決定在這裏分享這個解決方案。如何使用JPA(或Hibernate)註釋創建複合主文件

問題: 我在我的一個表中有一個複合主鍵。我需要將其與JPA註釋映射。

我POJO1:

public class Alarm { 

    @Id 
    @Column(name="alm_id") 
    private String id; 

    @Column(name="alm_description") 
    private String desc; 

    @ManyToOne 
    @JoinColumn(name = "alm_norm_id") 
    private Alarm normAlarm; 

    //getters and setters 
} 

我POJO2:

public class Equipment { 

    @Id 
    @Column(name="equ_id") 
    private String id; 

    @Column(name="equ_fixed_asset") 
    private String fixedAsset; 

    @Column(name="equ_service_tag") 
    private String serviceTag; 

    //getters and setters 

} 

所以我有一個表,該表的主鍵是一個Equipment + Alarm,我需要映射這一點。

回答

0

我不想創建一個單獨的類,僅用於處理與@IdClass註釋的主鍵。所以我決定改用@EmbeddedId@Embeddable註釋。結果是:

@Entity 
@Table(name="Alarm_Counter") 
public class Counter { 

    @EmbeddedId 
    private CounterId id; 

    @Column(name="aco_counter") 
    private int counter = 1; 

    @Column(name="aco_last_reset") 
    private Date resetDate; 

    public Counter(){} 

    public Counter(CounterId id) { 
     super(); 
     this.id = id; 
    } 


    //Getters and Setters 

    //... 

    //Embeddable class for handling primary key 
    @Embeddable 
    public class CounterId implements Serializable{ 

     /** 
     * 
     */ 
     private static final long serialVersionUID = 1L; 

     @ManyToOne 
     @JoinColumn(name="aco_alarm_id") 
     private Alarm alarm; 

     @ManyToOne 
     @JoinColumn(name="aco_equipment_id") 
     private Equipment equipment; 

     //Default Constructor 
     public CounterId(){} 

     //Constructor with fields 
     public CounterId(Alarm alarm, Equipment equipment) { 
      super(); 
      this.alarm = alarm; 
      this.equipment = equipment; 
     } 

     //Getters and Setters 
    } 
} 

我仍然需要處理這個對象用於保持它與休眠。所以我做了如下:

Alarm al = alarmService.get(alarm);     //Retrieve an Alarm object 
Equipment eq = equipmentService.get(equipment);  //Retrieve an Equipment object 

Counter ct = new Counter();       //Instantiates a Counter object 
CounterId cId = ct.new CounterId(alarm, equipment); //Instantiates a CounterId object (composite primary key for Counter) 

ct.setId(cId);          //Sets the primary key (CounterId) 
+0

那麼,你仍然最終創建一個內部類。如果你想,你也可以爲'@ IdClass'創建一個內部類。但作爲一種方法,'@ Embeddable'和'@ EmbeddedId'是更現代的。 –

+0

是的,我喜歡創建一個嵌入式類而不是創建太多分離的文件。謝謝;) –