Problem updating existing record, when using @Version annotation for optimistic locking.
Having a table (say: "X") with this annotation-approach:
@Id() @GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name="calcid")
private int calcId;
@Version @Column(name="version")
protected Integer version;
Using this approach (pp is a singleton persistency provider):
Fetching records:
Session session = [my persistency provider singleton].openSession();
session.beginTransaction();
List<X> xx = session.createQuery("from x",X.class).getResultList();
pp.closeSession();
return xx
Changing a record x from the xx-list and putting this (and only this) into a list, sent to the merging routine (Don't be confused about the list - there is only one record - the changed one - in it, but this way I am prepared for merging multiple records):
Merging same record
Session session = [my persistency provider singleton].openSession();
session.beginTransaction();
xx.forEach(x -> { session.merge(x);});
try {
session.getTransaction().commit();
} catch (OptimisticLockException e) {
pp.closeSession();
throw e;
}
pp.closeSession();
Though I can inspect the @Id just before the merge and see that it is the same as the originally fetched record's, the result is a new record with a new id.
If I simply remove the version annotation (and version field) the merge behaves as expected (exact same code as above, just no @Version and version-column), updating the existing record.
Note that even though the problem seems related to the @Version'ing involved in an optimistic locking approach, in the above example, only one session is involved.
It seems as if the @version alone makes Hibernate consider the original instance as new (even though Id is the same) and therefore creating a new with a new id.
New to Hibernate, so TIA for any help!
Using MariaDB (FKA MySQL) version 10. Hibernate 5 and this cfg:
<?xml version="1.0" encoding="UTF-8"?>
<!-- <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 5.3//EN" "http://www.hibernate.org/dtd/hibernate-configuration-5.3.dtd"> -->
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN">
-<hibernate-configuration>
-<session-factory>
<!-- <property name="hbm2ddl.auto">update</property> -->
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">xxx</property>
<property name="connection.password"/>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.show_sql">false</property>
<mapping class="niels.test.Test"/>
</session-factory>
</hibernate-configuration>
Best regards