java - How to create a composite primary with JPA (or Hibernate) annotations -
i got problem common problem , decided share resolution here.
the problem: have composite primary key in 1 of tables. need map jpa annotations.
my 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 , setters }
my 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 , setters }
so have table primary key equipment
+ alarm
, need map that.
i didn't want create separate class handle primary key @idclass
annotation. decided use @embeddedid
, @embeddable
annotations instead. 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 , setters //... //embeddable class 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 fields public counterid(alarm alarm, equipment equipment) { super(); this.alarm = alarm; this.equipment = equipment; } //getters , setters } }
i still needed handle object persist hibernate. made following:
alarm al = alarmservice.get(alarm); //retrieve alarm object equipment eq = equipmentservice.get(equipment); //retrieve equipment object counter ct = new counter(); //instantiates counter object counterid cid = ct.new counterid(alarm, equipment); //instantiates counterid object (composite primary key counter) ct.setid(cid); //sets primary key (counterid)
Comments
Post a Comment