1

我使用以下代码,当我从表中读取条目(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 值时,出现以下错误:

异常描述:[DerbyModel.Person] 类的属性[id] 映射到数据库中的主键列。不允许更新。线程“主”javax.persistence.RollbackException 中的异常:异常 [EclipseLink-7251] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345):org.eclipse.persistence.exceptions.ValidationException 异常描述:属性 [id] 的类 [DerbyModel.Person] 映射到数据库中的主键列。不允许更新。

4

1 回答 1

1

When calling em.persist(object), the instance refered by object is probably assigned an id by the dbms, and remains attached to the jpa session. This means that the instance object refers to is already persisted, and subsequent calls to persist will do nothing besides from trying to persist it again (same id, same values).

You'd probably need to create new instances of Person at every execution of the loop, and persist each one of them, or try to detach the instance (by means of em.detach(), for instance) and reset its id.

Untested sample:

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();
于 2013-01-24T10:20:47.580 回答