[英]How to create a composite primary with JPA (or Hibernate) annotations
I got this problem which is a very common problem and I decided to share the resolution here. 我遇到了一个非常普遍的问题,因此我决定在此分享解决方案。
The Problem: I have a composite primary key in one of my tables. 问题:我的一个表中有一个复合主键。 I need to map this with JPA annotations.
我需要使用JPA注释对此进行映射。
My POJO1: 我的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
}
My POJO2: 我的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
}
So I have a table which the primary key is an Equipment
+ Alarm
and I need to map that. 因此,我有一个表,其主键是“
Equipment
+ Alarm
,我需要对其进行映射。
I didn't want to create a separate class just for handle the primary key with @IdClass
annotation. 我不想创建一个单独的类仅用于处理带有
@IdClass
批注的主键。 So I decided to use @EmbeddedId
and @Embeddable
annotations instead. 所以我决定改用
@EmbeddedId
和@Embeddable
注解。 The result was: 结果是:
@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
}
}
I still needed to handle this object for persist it with hibernate. 我仍然需要处理该对象以使其保持休眠状态。 So I made the following:
所以我做了以下事情:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.