我使用以下代码,当我从表中读取条目时(derby db - eclipse 链接) 只有一个条目,我该如何添加新条目?例如添加相同条目 5 次?
for (Object object : listClsObj) {
int cnt = 1;
do {
em.getTransaction().begin();
em.persist(object);
em.getTransaction().commit();
cnt++;
}
while (cnt < 6);
}
em.close();
实体类是:
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private String id;
private String firstName;
private String lastName;
public String getId() {
return id;
}
public void setId(String Id) {
this.id = Id;
}
public String getFirstName() {
return firstName;
}
当我在 em persist 处放置断点并在第二个循环中更改 id 值时,出现以下错误:
Exception Description: The attribute [id] of class [DerbyModel.Person] is mapped to a primary key column in the database. Updates are not allowed. Exception in thread "main" javax.persistence.RollbackException: Exception [EclipseLink-7251] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.ValidationException Exception Description: The attribute [id] of class [DerbyModel.Person] is mapped to a primary key column in the database. Updates are not allowed.
最佳答案
当调用em.persist(object)
时,object
引用的实例可能由dbms分配一个id
,并保持附加到jpa session 。这意味着 object
引用的实例已经被持久化,并且后续调用 persist
除了尝试再次持久化它(相同的 id,相同的值)之外不会执行任何操作。
您可能需要在每次执行循环时创建 Person
的新实例,并保留每个实例,或者尝试分离该实例(例如,通过 em.detach()
)并重置其 id。
未经测试的示例:
for (Object object : listClsObj) {
int cnt = 1;
do {
em.getTransaction().begin();
em.persist(object);
em.getTransaction().commit();
em.detach(object);
((Person)object).setId(null);
cnt++;
}
while (cnt < 6);
}
em.close();
关于java - 使用 JPA 将新实例添加到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14498216/