ok, i made a spimpler test case and i've found where the problem exactly is. semi pseudo code follows:
Code:
class A {
@id //generated in the contructor
UUID id;
@version
Long version;
@column(unique=true)
Long uniqueField;
@ManyToOne
B connectedEntity;
}
class B {
@Id //generated in the contructor
UUID id;
@Version
Long version;
}
a = new A();
//B with id 2 is in the database, version=0
a.setConnectedEntity(find(B.class,2));
//a record with unique 0 already exists in the database
a.setUniqueField(0);
try {
transaction.begin();
merge(a);
transaction.commit();
} catch(exception e) {
//Exception thrown because of the unique violation
transaction.begin();
a.setUniqueField(a.getUiniqueField() + 1));
merge(a);
transaction.commit();
}
the second merge causes the OptimisticLockException only if i set the connected entity (that is versioned and already in the db but not modified in current transactions...)
I hope this clarify the whole thing to whom can explain me how to avoid the Exception.