Spring Hibernate getCurrentSession()删除不起作用 [英] Spring Hibernate getCurrentSession() delete not working
问题描述
我在单元测试中完全测试了一个实体,到目前为止,几乎所有的工作都有效:创建,更新,列表。但是,当我尝试删除记录时,它不会被删除。这是我使用的代码:
public void delete(Integer id){
//这甚至不起作用但我知道用户设置和ID不为空
用户用户=查找(ID);
getSession()。delete(user);
//这将工作
// Query query = getSession()。createSQLQuery(DELETE FROM users WHERE id =+ id);
// query.executeUpdate();
$ b private session getSession(){
if(session == null){
try {
session = SessionFactoryUtils.getSession(sessionFactory,Boolean 。真正);
TransactionSynchronizationManager.bindResource(session.getSessionFactory(),new SessionHolder(session));
} catch(Exception e){
session = SessionFactoryUtils.getSession(sessionFactory,Boolean.FALSE);
}
}
返回会话;
$ b如果我直接执行查询,它可以工作,但使用delete()方法不会。我认为这可能与交易有关,但我已经尝试过这样的事情,但没有运气。任何想法?
解决方案我发现这个问题。
首先,find()方法正在驱逐我的用户模型,并可能将它从会话中删除。
删除()后,我还需要session.flush( )
I am fully testing an entity on my unit test, and almost everything worked so far: create, update, list. However, when I try to delete a record, it is not getting deleted. Here is the code I am using:
public void delete (Integer id) {
// This doesnt work even though I know user is set and id is not null
User user = find(id);
getSession().delete(user);
// This will work
// Query query = getSession().createSQLQuery("DELETE FROM users WHERE id = " + id);
// query.executeUpdate();
}
private Session getSession() {
if (session == null) {
try {
session = SessionFactoryUtils.getSession(sessionFactory, Boolean.TRUE);
TransactionSynchronizationManager.bindResource(session.getSessionFactory(), new SessionHolder(session));
} catch (Exception e) {
session = SessionFactoryUtils.getSession(sessionFactory, Boolean.FALSE);
}
}
return session;
}
If I execute the query directly it works but using the delete() method doesnt. I think it may be related to committing the transaction but I already tried something like that and no luck. Any ideas?
解决方案 I found the problem with this one.
First, find() method was evicting my user model, and probably taking it out of the session.
After delete(), I also needed to session.flush()
这篇关于Spring Hibernate getCurrentSession()删除不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!