JPA 保留具有复合主键的表对象列表
我需要保存具有复合主键的表的对象列表,我正在这样做,如下所示。但我收到错误 Caused by: java.sql.BatchUpdateException: ORA-00001: 违反了唯一约束。 但列表中的项目是唯一的,我做错了什么。
// 表结构
@Entity
@Table(name="COMP_PRIMARY")
CompPrimaryObj{
@Id
@Column(name="KEY1")
private String key1;
@Id
@Column(name="KEY2")
private Long key2;
}
// 我的服务层中的代码
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
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
处理复合主键时,您有两种选择。在每个类中,您都必须创建一个新类来保存表示 PK 的字段:
复合主键:
或带有嵌入式主键:
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:
Or with Embedded Primary Keys:
最近我用复合主键映射了@Many-To-Many。看看这篇文章,我认为它可以为您提供所有必需的信息。
使用复合主键和注释映射多对多:
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: