gpt4 book ai didi

java - 使用 JPA 将新实例添加到表中

转载 作者:太空宇宙 更新时间:2023-11-04 07:50:49 25 4
gpt4 key购买 nike

我使用以下代码,当我从表中读取条目时(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com