我正在尝试使用版本字段使用乐观锁定,并且当我从 jpa 存储库调用保存时没有抛出异常。我是 Spring 和 hibernate 的新手,我担心我设置不正确。
我正在使用的库是:
hibernate4-maven-plugin 版本 1.0.2
hibernate -jpa02.0 1.0.1
spring-data-jpa 版本 1.3.4
所以我的实体是这样设置的:
@Entity
public class MyEntity
{
@Id
protected Long id;
@Version
protected Long version;
protected String name;
public Long getVersion()
{
return version;
}
public void setVersion(Long version)
{
this.version = version;
}
public Long getVersion()
{
return version;
}
public void setVersion(Long version)
{
this.version = version;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(Long id)
{
this.name = name;
}
}
我通过我的 dto 将版本传递给客户端,并在我在 MyEntityStoreDao 中进行保存时将其传回:
@Repository
public class MyEntityStoreDao extends BaseDao<MyEntityStoreDao>
{
private RepositoryManager myRepoManager;
@Autowired
public void setMyRepo(MyEntityRepository myRepo)
{
this.myRepo = myRepo;
}
public MyEntity save(MyEntityDTO dtoToUpdate)
{
Session session = this.Session();
MyEntity myEntity = new MyEntity();
if(dtoToUpdate.getId() > 0) {
myEntity = (MyEntity) session.get(MyEntity.class, dtoToUpdate.getId())
}
myEntity.setName(dtoToUpdate.getName());
MyEntity result = this.myRepo.save(myEntity);
this.repositoryManager.flush(myRepo);
}
}
repositoryManager 位于 BaseDao 中并使用 org.springframework.data.jpa.repository.JpaRepository
。
版本正在正确更新和递增。但是当我进行更新时,我预计当从 DTO 传递的版本保存在 MyEntityStoreDao 中时与数据库中的内容不匹配时,它会抛出 StaleStateException 或 OptmisticLockingException。
我检查过,版本不匹配,但保存仍然发生。关于为什么会发生这种情况的任何帮助?谢谢
最佳答案
通过 show-sql=true 打开 sql 日志记录并查看更新查询是否具有所需的 where 子句
where version = ?
如果缺少这样的 where 子句,则需要添加注释 @org.hibernate.annotations.Entity(dynamicUpdate = true)
关于java - 使用版本的 Hibernate 乐观锁定不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21832573/