为什么在删除实体时出现StaleObjectStateException? [英] Why do I get a StaleObjectStateException on removing entity?
问题描述
在Spring Boot Web应用程序中,我有一个控制器,该控制器提供了一种从数据库中删除实体的方法,该方法又称为DAO类.但是,当我调用entityManager.remove(entity)
时,即使从数据库中检索到entity
,我仍然收到一个StaleObjectStateException
,并且没有其他可能更改entity
的API调用.
In my Spring Boot web app, I have a controller, which provides a method to remove an entity from the database, which in turn calls a DAO class. However, when I call entityManager.remove(entity)
, I receive a StaleObjectStateException
, even though entity
was just retrieved from the database and there was no other call to my API which may have altered entity
.
这是我的控制者:
@Transactional
@RestController
public class AppAdminController {
...
@RequestMapping(value = "/admins/{username}", method = RequestMethod.DELETE)
public void deleteAdmin(@PathVariable("username") String username) {
dao.removeByUsername(username);
}
}
DAO:
@Service
public class AppAdminDao extends AbstractDAO<UUID, AppAdmin> {
public AppAdmin getByUsername(String username) {
TypedQuery<AppAdmin> query = em.createQuery("SELECT a FROM AppAdmin a WHERE a.username=:username", AppAdmin.class);
query.setParameter("username", username);
try {
return query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
public void removeByUsername(String username) {
AppAdmin admin = getByUsername(username);
if(admin != null) {
em.remove(admin);
}
}
}
通过调用
AppAdmin res = em.merge(aa);
,甚至在添加实体后立即调用em.remove(res)
都会产生上述异常.我在做什么错了?
and even calling em.remove(res)
immediately after adding the entity yields the exception mentioned above. What am I doing wrong?
推荐答案
在PaulNUK的提示下,我向我的实体添加了一个带@Version
注释的字段.现在,在将实体添加到数据库中时,我收到以下异常:org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
.
Following the hint of PaulNUK, I added an @Version
annotated field to my entity. Now I received the following exception on adding an entity to my database: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
.
原来是问题所在:我的实体有一个UUID作为ID,其注释如下:
The problem turned out to be the following: My entity has a UUID as an id, which was annotated as follows:
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
添加
@Column(columnDefinition = "BINARY(16)")
解决了问题.
这篇关于为什么在删除实体时出现StaleObjectStateException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!