2 Replies Latest reply on May 30, 2013 5:16 PM by 635546

    persist does not throw any exception in a JUnit test

      I am implementing a JUnit test using Toplink as JPA provider. I must be missing something because I try to persist two times the same entity and no exception is thrown. Neither PersistenceException nor any other type of exception. The code cannot be easier:

      public void testAddExistingTeam() throws Exception {

      Team team = new Team("team2");


      EntityManagerFactory emf =
      EntityManager em = emf.createEntityManager();



      catch(Exception e){


      Notice the two em.persist(team).

      This code does not seem to either enter the catch block or produce any sort of exception. On the other hand, I have checked that after the first
      em.persist(team); the team is really managed.

      The relevant parts of the Team class definition follow:

      @Table (name ="TEAM")
      public class Team implements Serializable {
      @Column (name="NAME")
      private String name;

      @JoinColumn (name="CLUB_NAME", referencedColumnName="NAME")
      private Club club;
      private Category category;
      private String email;

      private List<Competition> competitions;

      public Team (String name){
      this.name = name;
      this.club = null;
      this.competitions = new ArrayList<Competition>();

      ....getters/setters....and more constructors.

      I am really puzzled by this issue. Somebody could help??? I would be really grateful!!!

        • 1. Re: persist does not throw any exception in a JUnit test
          This is expected behavior as persist is a no-op if called on a managed entity (other than to cascade over relationships marked with cascade.Persist), and the first persist call makes the passed in team entity managed.

          Try calling em.flush(); and em.clear(); between the persist calls to get an exception.
          The first flush will ensure the team is inserted in the database, while clear will detach it so that the second persist call will try to insert the team. JPA providers are not required to throw the entityExistsException on persist - it can be delayed until the transaction is flushed or committed, so you are likely to get a PersistenceException from the commit instead of EntityExistsException from persist.

          Best Regards,
          • 2. Re: persist does not throw any exception in a JUnit test
            Thank you so much!!!

            The behaviour is exactly as you predicted. persist is a no-op operation if it applies to a managed entity. It is clear (the worst thing is that I knew it!!!!). Thank you very very much again.!!!!