Search code examples
javadatabasejpaeclipselinkderby

Add new Instances to tables using JPA


I using the following code and when I read the entry from the tables (derby db - eclipse link) there is just one entry ,how should I add new entries? for example to add same entry 5 times ?

for (Object object : listClsObj) {
    int cnt = 1;
    do {
        em.getTransaction().begin();
        em.persist(object);
        em.getTransaction().commit();
        cnt++;
    }
    while (cnt < 6);
        }
em.close();

The entity class is :

@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;
}

When I put breakpoint at em persist and in the second loop change the id value I got the following error :

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.


Solution

  • 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();