Reputation: 147
I need to save a list of objects of a table with composite primary key, I am doing as shown below. But I am getting an error Caused by: java.sql.BatchUpdateException: ORA-00001: unique constraint violated. But the items in the list are unique, what am I doing wrong.
// Table structure
@Entity
@Table(name="COMP_PRIMARY")
CompPrimaryObj{
@Id
@Column(name="KEY1")
private String key1;
@Id
@Column(name="KEY2")
private Long key2;
}
// code in my service layer
List<CompPrimaryObj> compPrimaryObjList = new ArrayList<CompPrimaryObj>();
CompPrimaryObj obj1 = new CompPrimaryObj();
obj1.setKey1("key1");
obj1.setKey2(11111);
compPrimaryObjList.add(obj1);
CompPrimaryObj obj2 = new CompPrimaryObj();
obj2.setKey1("key2");
obj2.setKey2(222222);
compPrimaryObjList.add(obj2);
for(CompPrimaryObj compPrimaryObj:compPrimaryObjList){
em.persist(compPrimaryObj); // em stands for Entity manger instance
}
Upvotes: 0
Views: 2690
Reputation: 27880
When dealing with a composite primary key, you have two options. In each of them, you've got to create a new class to hold the fields that represent the PK:
Composite Primary Key:
@Entity
@Table(name="COMP_PRIMARY")
@IdClass(CompPrimaryObjId.class)
public class CompPrimaryObj {
@Id
@Column(name="KEY1")
String key1;
@Id
@Column(name="KEY2")
Long key2;
//...
}
public class CompPrimaryObjId{
String key1;
Long key2;
}
Or with Embedded Primary Keys:
@Embeddable
public class CompPrimaryObjId {
@Column(name="KEY1")
private String key1;
@Column(name="KEY2")
private Long key2;
// ...
}
}
@Entity
@Table(name="COMP_PRIMARY")
public class CompPrimaryObj {
@EmbeddedId
private CompPrimaryObjId id;
//....
}
Upvotes: 1
Reputation: 18639
Recently I mapped @Many-To-Many
with Composite primary keys. Look at this post I think it can give you all required information.
Mapping ManyToMany with composite Primary key and Annotation:
Upvotes: 0