Question

I have an entity like this:

  @Entity
  @Table(name = "PERSON_TB") {
  public class Person implements Serializable {

         private static final long serialVersionUID = 3433ba34234aL;

         @Id
         @Column(name = "ID")
         private Long personId;

         @Column(name = "NAME")
         private String name;

         @Column(name = "UPDATE_DATE")
         private Date updatedDate;

         //getters and setters
  }

I have a code that generates HQL:

  Update Person p set p.updatedDate = :dt_1 where p.personId = :pid_1,
                      p.updatedDate = :dt_2 where p.personId = :pid_2
                      ....

Code to execute the update:

    @SuppressWarnings("unchecked")
    @TransactionAttribute(TransactionAttributeType.MANDATORY)
    public int executeUpdate(String sql, Map<String, Object> params) {

       Query query = getEntityManager().createQuery(sql);

       for (Entry<String, Object> entry : params.entrySet()) {
          query.setParameter(entry.getKey(), entry.getValue());
       }

       int rows = query.executeUpdate();
       return rows;     
    }

Questions:

  1. Does optimistic lock come into picture here? Does Hibernate automatically take care of Optimistic locking in the above case (running HQL and with no sessions)?
  2. In case the above is not true and I need to implement on my own: I read Hibernate docs that says, I need to annotate a field with @Version. But should I add this new field in the table specifically for this? or I can designate any existing fields for @Version annotation? Any special handling here?
  3. The exception thrown during the optimistic locking is StaleObjectStateException? So when an exception is thrown, I can be sure its an optimistic lock exception? Any other use cases. The reason is, I need to inform the user accordingly.
Was it helpful?

Solution

  1. If you don't have any field annotated with @Version, Hibernate can't do optimistic locking.
  2. The point of having an @Version field is precisely to avoid implementing your own optimistic locking. Hibernate will use the field annotated with @Version to implement optimistic locking. The way it works is described in the documentation. Note that update queries will bypass optimistic lock verifications completely. They can update the version field, but only when using a versioned update.
  3. The exception javadoc explains when such an exception is thrown.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top