title: Deleting an object by its ID and version in JPA
body: <p>I am learning JPA, and I am trying to use it in a Spring MVC web app. I need to implement a method that deletes an object/record. Currently, I have the following implementation of the method:</p>
  
  <pre><code>@Transactional
  public void deleteProduct(int productId, int productVersion) {
  
      Product product = entityManager.find(Product.class, productId);
      product.setVersion(productVersion);
      entityManager.remove(product);
  }
  </code></pre>
  
  <p><code>productVersion</code> is used for optimistic locking. It is the old version of the object/record that comes from the web GUI. </p>
  
  <p>This method deletes the record in the DB, but it does not throw any exception when the version of the record in the DB does not match <code>productVersion</code>. (I only have a problem with <strong>deleting</strong> objects: when I <strong>update</strong> a record with <code>entityManager.merge(product)</code>, I get an exception with the message: <code>Row was updated or deleted by another transaction</code>.)</p>
  
  <p>Hibernate generates the following SQL query: <code>delete from Product where id=? and version=?</code>, i.e. it tries to check the <code>version</code> field.</p>
  
  <p>What am I doing wrong?</p>
  
  <p>Also, is it a correct approach to removing an object by its id? I am concerned that my method generated two SQL queries: a <code>SELECT</code> for <code>entityManager.find()</code>, and a <code>DELETE</code> for <code>entityManager.remove()</code>. Is there a more optimal way to delete an object/record?</p>
  
  <p><strong>Product class</strong></p>
  
  <pre><code>@Entity
  public class Product {
  
      @Id
      @GeneratedValue
      protected int id;
  
      protected String name;
  
      protected BigDecimal price;
  
      @Version
      protected int version;
  
      // getters and setters
  }
  </code></pre>