我在Hibernate中使用乐观锁定(通过@Version
获取我的bean的版本属性)。因此,在发生冲突的更改时会抛出OptimisticLockException
。
但是-没想到:抛出此异常时,我的bean的version属性会自动设置为实际(数据库)值,而其他属性仍然是旧值。因此,如果我第二次对此对象进行更新,将不再抛出OptimisticLockException
(因为版本不再相同),并且该对象中的数据将覆盖数据库状态。
这是预期的行为吗?
编辑:
MyBean:
@Entity
@Table(schema = "my_schema", name = "my_bean")
public class MyBean {
...
@Version
@Column(name = "version")
private int version;
...
}
读:
CriteriaQuery<MyBean> criteriaQuery = (CriteriaQuery<MyBean>)criteriaBuilder.createQuery(MyBean.class);
Root<MyBean> root = criteriaQuery.from(MyBean.class);
Expression<Integer> expr = (Expression<Integer>)root.get(MyBean_.id);
criteriaQuery.where(criteriaBuilder.equal(expr, 1));
Query q = currentSession.createQuery(criteriaQuery);
MyBean myBean = (MyBean)q.getResultList().get(0);
System.out.println("Version after read:" + myBean.getVersion();
写:
System.out.println("Version before update:" + myBean.getVersion();
try {
myBean.setText("test");
transaction = session.beginTransaction();
session.update(myBean);
transaction.commit();
}
catch (Exception exc) {
exc.printStackTrace();
transaction.rollback;
session.close();
}
System.out.println("Version after update:" + myBean.getVersion();
正在记录:
Process 1: "Version after read: 1"
Process 2: "Version after read: 1"
Process 1: "Version before update: 1"
Process 1: "Version after update: 2"
Process 2: "Version before update: 1"
javax.persistence.OptimisticLockException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.internal.ExceptionConverterImpl.wrapStaleStateException(ExceptionConverterImpl.java:214) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:88) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1443) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
Process 2: "Version after update: 2"
最佳答案
否,这不是预期的行为。在OptimisticLockException
的情况下版本不应递增。请检查是否已更新任何链接的子实体,但是在上级实体更新OptimisticLockException
期间发生,反之亦然。