title: ConstraintViolationException thrown for Foreign Key
body: <p>I am getting a ConstraintViolationException when I try to saveOrUpdate using hibernate. When I insert a brand new object for a user, the save works perfectly but when I try to update it fails. </p>
  
  <p>In the database table I have a unique not null primary key and a unique not null foreign key named userid </p>
  
  <p>My pojo declaration is as follows;</p>
  
  <pre><code>@Id @GeneratedValue
  @Column(name = "id")
  private int id;
  
  @Column(name="userid")
  private int userid;
  
  @Column(name = "homephonenumber")
  protected String homeContactNumber;
  
  @Column(name = "mobilephonenumber")
  protected String mobileContactNumber;
  
  @Column(name = "photo")
  private byte[] optionalImage;
  
  
  @Column(name = "address")
  private String address;
  </code></pre>
  
  <p>My insert statement looks as follows;</p>
  
  <pre><code>public boolean addCardForUser(String userid, Card card) {
  
      if(StringUtilities.stringEmptyOrNull(userid)){
          throw new IllegalArgumentException("Cannot add card for null or empty user id");
      }
  
      if(card == null){
          throw new IllegalArgumentException("Cannot null card to the database for user " + userid);
      }
  
      SessionFactory sf = null;
      Session session = null;
  
      try{
          sf = HibernateUtil.getSessionFactory();
          session = sf.openSession();
          session.beginTransaction();
  
          session.saveOrUpdate(card);
          session.getTransaction().commit();
          return true;
      }catch(Exception e){
          logger.error("Unable to add Card to the database for user " + userid );
      }finally{
          DatabaseUtilities.closeSessionFactory(sf);
          DatabaseUtilities.closeSession(session);
      }
      return false;
  }
  </code></pre>
  
  <p>The exception I get says</p>
  
  <blockquote>
    <p>com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
    Duplicate entry '16' for key 'userid_UNIQUE'</p>
  </blockquote>
  
  <p>And the database looks like this</p>
  
  <p><img src="https://i.stack.imgur.com/SsmXC.png" alt="enter image description here"></p>
  
  <p>What am I doing wrong, should the database entry not be updated?</p>