Spring Hibernate getCurrentSession()删除不起作用

时间:2014-03-14 20:58:44

标签: java spring hibernate

我在单元测试中完全测试了一个实体,到目前为止几乎所有工作都有效:创建,更新,列表。但是,当我尝试删除记录时,它不会被删除。这是我正在使用的代码:

  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;
    }

如果我直接执行查询它可以工作,但使用delete()方法不行。我认为这可能与提交交易有关,但我已经尝试过这样的事情而且没有运气。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我发现了这个问题。

首先,find()方法正在逐出我的用户模型,并可能将其从会话中删除。

删除()后,我还需要session.flush()