title: Using JPA/Hibernate and Entity update column on unique contraint violation
body: <p>I have a PUT call that, via <code>@RequestBody</code>, will map the payload to the below Object:</p>
  
  <pre><code>@Entity
  @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"clientId", "reasonCode"}))
  public class DeviceInfo implements Serializable {   
      @Id 
      @GeneratedValue(strategy=GenerationType.IDENTITY)
      private long id;
  
      private int clientId;
  
      private String reasonCode;
  
      private int deviceValue;
  
      ... Getters and Setters here ....
  }
  </code></pre>
  
  <p>For the DAO layer I have this simple Interface</p>
  
  <pre><code>public interface DeviceInfoDao extends JpaRepository&lt;DeviceInfo, Long&gt; {
  
  }
  </code></pre>
  
  <p>which using Spring gets <code>@Autowired</code> into my Service layer and saves the Object to the DB with </p>
  
  <pre><code>deviceInfo = deviceInfoDao.save(deviceInfo);
  </code></pre>
  
  <p>The issue I am running into is, I could later have another PUT call where the payload is the same except this time the deviceValue is different. Currently it will throw an Exception because the <code>@UniqueConstraint</code> was violated.</p>
  
  <p>However, what I would prefer is that an update happens when DeviceInfoDao.save() gets called rather than an Exception getting thrown. I am new to JPA and Hibernate so if someone could please give "best practice" or the cleanest way to do this I would greatly appreciate it.</p>
  
  <p>As a side note - </p>
  
  <ol>
  <li><p>I know throwing an Exception (or sending some kind of error) and forcing the user to use the <code>PATCH</code> HTTP method would probably be the best practices scenario here but requirements dictate I do it this way.</p></li>
  <li><p>The caller won't know the auto-generated id value that was produced so having them send that on the next call is not an option.</p></li>
  </ol>