我在Hibernate中使用乐观锁定(通过@Version
获取我的bean的version-attribute)。因此,在发生冲突的更改时,会抛出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"
答案 0 :(得分:0)
这不是预期的行为。在OptimisticLockException
的情况下,版本不应该增加。请检查是否有任何链接的子实体更新,但在父实体更新OptimisticLockException
期间发生,反之亦然。< / p>