7 Replies Latest reply on Mar 9, 2008 10:03 PM by Keith Naas

    How do I use EntityManager in a Bean with foreign key constraints

    Newbie

      Hello, I have a table persons with a unique key on (department, title, first_name, last_name).


      My bean looks something like this:


      @Stateful @Name("personUpload")
      public class PersonUploadBean implements PersonUpload
      {
        @In EntityManager em;
      
        public void fileUpload()
        {
          ArrayList<Person> oldPs = (ArrayList<Person>) em.createQuery("from Person").getResultList();
          ArrayList<Person> oldPs = getNewPersonsFromCSV();
          for(Person oP:oldPs) { em.remove(oP); }
          for(Person nP:newPs) { em.persist(nP); }
        }
      }
      



      It does the right thing (deleting all old entries and creating new ones) when I call it with a file, that contains only persons that do not match a constraint.


      But when I use the same file a second time I get this exception:


      WARN  [JDBCExceptionReporter] SQL Error: 1062, SQLState: 23000
      ERROR [JDBCExceptionReporter] Duplicate entry 'EWZ-Dr.-Patrick-Master' for key 2
      FATAL [application] javax.ejb.EJBTransactionRolledbackException: org.hibernate.exception.ConstraintViolationException: could not insert: [de.gdc.Person]
      javax.faces.el.EvaluationException: javax.ejb.EJBTransactionRolledbackException: org.hibernate.exception.ConstraintViolationException: could not insert: [de.gdc.Person]
                ...



      Do I have to commit (what?) between the removes and the persists or did I miss something relevant?


      Thanks in advance, Peter