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

标签 java database jpa eclipselink derby

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

相关文章:

MySQL : "Appending more data to a column"

java - 为什么 Hibernate 会阻止 Java 进程退出?

java - 具有抽象泛型和集合的 JPA 单表继承

java - Java中使用参数实例化变量

sql - 将查询与 SQL 中的正则表达式匹配?

php - 无法从数据库中选择记录

java - 数据库和 JPA 中不同的 PostgreSQL 序列 ID

java - 在避免实现继承和保持内部化的同时最大化代码重用的最佳方法

java - Android Studio Assets 字体文件夹

Java GUI 问题(布局管理器)