title: Duplicate key issue with Spring and Hibernate - assistance needed
body: <p>--Summary (shortened)--</p>
  
  <p>I have a controller that loads a profile object from the corresponding DAO.  It updates some properties, many of them sets, and then calls saveOrUpdate (via save in the DAO) to reattach and update the profile object.  At seemingly random intervals, we get an org.hibernate.exception.ConstraintViolationException, with a root cause: Caused by: java.sql.BatchUpdateException: Duplicate entry '3-56' for key 1.  The stack trace points to the saveOrUpdate method called from the profile update controller.  I can't replicate in my test environment, we only see this in production, so I'm wondering if I'm missing something thread-safety related (which is why I'm posting so much code/configuration info).  Any ideas?</p>
  
  <p>-- Code --</p>
  
  <p>I've tried to provide as much relevant configuration/code as possible - let me know if more is needed:</p>
  
  <p>Here is an excerpt from the offending controller:</p>
  
  <pre><code>public class EditProfileController extends SimpleFormController {
  
  protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception
  {
      if(!checkLoggedIn(request))
      {
          return new ModelAndView("redirect:" + invalidRedirect);
      }
  
      HttpSession session = request.getSession();
      Resource resource = (Resource)session.getAttribute("resource"); //The resource object is stored in session upon login and upon account creation.
      Profile profile = profiles.getProfileByResource(resource);
  
      if(profile == null)
      {
          profile = new Profile();
          profile.setResource(resource);
      }
  
      //I use custom editors to populate the sets in the command object with objects based on the selection
  
      if(profile.getPrimaryRoleSkills() != null &amp;&amp; editProfileCommand.getPrimaryRoleSkills() != null)
      {
          profile.getPrimaryRoleSkills().addAll(editProfileCommand.getPrimaryRoleSkills());
          profile.getPrimaryRoleSkills().retainAll(editProfileCommand.getPrimaryRoleSkills());
      }
      else
          profile.setPrimaryRoleSkills(editProfileCommand.getPrimaryRoleSkills());
  
      profiles.save(profile);  //This is the line that appears in the stack trace
      return new ModelAndView(getSuccessView());
  }
  //Other methods omitted
  }
  </code></pre>
  
  <p>Abbreviated Profile Class:</p>
  
  <pre><code>public class Profile  implements java.io.Serializable {
  
  private long id;
  private Resource resource;
  private Set&lt;PrimaryRoleSkill&gt; primaryRoleSkills = new HashSet&lt;PrimaryRoleSkill&gt;(0);
  
  public Profile() {
  }
  //Other properties trivial or similar to above.  Getters and setters omitted
  //toString, equals, and hashCode are all generated by hbm2java
  }
  </code></pre>
  
  <p>NameValuePairs base class (PrimaryRoleSkill extends this without adding anything):</p>
  
  <pre><code>public class NameValuePairs  implements java.io.Serializable {
  private long id;
  private String name;
  private boolean active = true;
  
  public NameValuePairs() {
  }
  //equals and hashCode generated by hbm2java, getters &amp; setters omitted
  } 
  </code></pre>
  
  <p>Here is my DAO base class:</p>
  
  <pre><code>public class DAO {
  
  protected DAO() {
  }   
  
  public static Session getSession() {
        Session session = (Session) DAO.session.get();
        if (session == null) {
           session = sessionFactory.openSession();
           DAO.session.set(session);
        }
        return session;
  }
  
  protected void begin() {
    getSession().beginTransaction();
  }
  
  protected void commit() {
    getSession().getTransaction().commit();
  }
  
  protected void rollback() {
    try {
    getSession().getTransaction().rollback();
    } catch( HibernateException e ) {
       log.log(Level.WARNING,"Cannot rollback",e);
    }
  
    try {
       getSession().close();
    } catch( HibernateException e ) {
       log.log(Level.WARNING,"Cannot close",e);
    }
    DAO.session.set(null);
   }
  
  public boolean save(Object object)
  {
     try {
          begin();
          getSession().saveOrUpdate(object);
          commit();
          return true;
      }
      catch (HibernateException e) {
          log.log(Level.WARNING,"Cannot save",e);
          rollback();
          return false;
      }
  }
  
  private static final ThreadLocal&lt;Session&gt; session = new ThreadLocal&lt;Session&gt;();
  
  private static final SessionFactory sessionFactory = new Configuration()
       .configure().buildSessionFactory();
  private static final Logger log = Logger.getAnonymousLogger();
  
  //Non-related methods omitted.
  }
  </code></pre>
  
  <p>Below is the important part of the Profiles DAO:</p>
  
  <pre><code>public class Profiles extends DAO {
  public Profile getProfileByResource(Resource resource)
  {
      try
      {
          begin();
          Query q = getSession().createQuery("from Profile where resource = :resource");
          q.setLong("resource", resource.getId());
          commit();
          if(q.uniqueResult() == null)
              return null;
  
          return (Profile) q.uniqueResult();
      }
      catch(HibernateException e)
      {
          rollback();
      }
      return null;
  }
  //Non-related methods omitted.
  }
  </code></pre>
  
  <p>Relevant Spring configuration:</p>
  
  <pre><code>&lt;bean id="profiles" class="com.xxxx.dao.Profiles" /&gt;
  
  &lt;bean id="editProfileController" class="com.xxxx.controllers.EditProfileController"&gt;
      &lt;property name="sessionForm" value="false" /&gt;
      &lt;property name="commandName" value="editProfileCommand" /&gt;
      &lt;property name="commandClass" value="com.xxxx.commands.EditProfileCommand" /&gt;
  
      &lt;property name="profiles" ref="profiles" /&gt;     
  
      &lt;property name="formView" value="EditProfile" /&gt;
      &lt;property name="successView" value="redirect:/profile" /&gt;
      &lt;property name="validator" ref="profileValidator" /&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>hibernate.cfg.xml</p>
  
  <pre><code>&lt;session-factory&gt;
      &lt;property name="connection.driver_class"&gt;@driver@&lt;/property&gt;
      &lt;property name="connection.url"&gt;@connectionurl@&lt;/property&gt;
      &lt;property name="connection.username"&gt;@dbuser@&lt;/property&gt;
      &lt;property name="connection.password"&gt;@dbpw@&lt;/property&gt;
      &lt;property name="dialect"&gt;org.hibernate.dialect.MySQLInnoDBDialect&lt;/property&gt;
      &lt;property name="dbcp.maxActive"&gt;15&lt;/property&gt;
      &lt;property name="dbcp.maxIdle"&gt;5&lt;/property&gt;
      &lt;property name="dbcp.maxWait"&gt;120000&lt;/property&gt;
      &lt;property name="dbcp.whenExhaustedAction"&gt;2&lt;/property&gt;
      &lt;property name="dbcp.testOnBorrow"&gt;true&lt;/property&gt;
      &lt;property name="dbcp.testOnReturn"&gt;true&lt;/property&gt;
      &lt;property name="dbcp.validationQuery"&gt;
          select 1
      &lt;/property&gt;
      &lt;property name="dbcp.ps.maxActive"&gt;0&lt;/property&gt;
      &lt;property name="dbcp.ps.maxIdle"&gt;0&lt;/property&gt;
      &lt;property name="dbcp.ps.maxWait"&gt;-1&lt;/property&gt;
      &lt;property name="dbcp.ps.whenExhaustedAction"&gt;2&lt;/property&gt;
  
      &lt;!-- Echo all executed SQL to stdout
      &lt;property name="show_sql"&gt;true&lt;/property&gt;
      --&gt;
  
      &lt;mapping resource="com/xxxx/entity/Resource.hbm.xml"/&gt;
      &lt;mapping resource="com/xxxx/entity/Authentication.hbm.xml"/&gt;
      &lt;mapping resource="com/xxxx/entity/NameValuePairs.hbm.xml"/&gt;
      &lt;mapping resource="com/xxxx/entity/Profile.hbm.xml"/&gt;
      &lt;mapping resource="com/xxxx/entity/FileData.hbm.xml"/&gt;
   &lt;/session-factory&gt;
  </code></pre>
  
  <p></p>
  
  <p>Excerpt from Profile.hbm.xml:</p>
  
  <pre><code>&lt;hibernate-mapping&gt;
  &lt;class name="com.xxxx.entity.Profile" select-before-update="true"&gt;
  &lt;id name="id" type="long"&gt;
          &lt;generator class="foreign"&gt;
              &lt;param name="property"&gt;resource&lt;/param&gt;
          &lt;/generator&gt;
  &lt;/id&gt;
  
  &lt;set name="primaryRoleSkills" cascade="none"&gt;
      &lt;key column="profile"/&gt;
      &lt;many-to-many column="primary_role_skill" class="com.xxxx.entity.PrimaryRoleSkill"/&gt;
  &lt;/set&gt;
  &lt;/class&gt;
  &lt;/hibernate-mapping&gt;
  </code></pre>
  
  <p>Excerpt from NameValuePairs.hbm.xml:</p>
  
  <pre><code>&lt;hibernate-mapping&gt;
  &lt;class name="com.xxxx.entity.NameValuePairs" abstract="true"&gt;
      &lt;id name="id" type="long"&gt;
      &lt;generator class="native" /&gt;
  &lt;/id&gt;
  &lt;discriminator column="type" type="string" /&gt;
      &lt;property type="string" name="name" length="256"&gt;
          &lt;meta attribute="use-in-equals"&gt;true&lt;/meta&gt;
      &lt;/property&gt;
      &lt;property type="boolean" name="active"&gt;
          &lt;meta attribute="default-value"&gt;true&lt;/meta&gt;
      &lt;/property&gt;
      &lt;subclass name="com.xxxx.entity.PrimaryRoleSkill" discriminator-value="PrimaryRoleSkill" /&gt;
      &lt;/class&gt;
  &lt;/hibernate-mapping&gt;
  </code></pre>
  
  <p>The application runs on Tomcat 6.0.14, and connects to MySQL version 5.0.89-community, running on Linux.  We are using Hibernate 3.3.2 and Spring Framework 2.5.6.</p>