繁体   English   中英

Spring Hibernate的getCurrentSession()删除不起作用

[英]Spring Hibernate getCurrentSession() delete not working

我正在单元测试中对一个实体进行全面测试,到目前为止,几乎所有工作都可以进行:创建,更新,列出。 但是,当我尝试删除记录时,它并没有被删除。 这是我正在使用的代码:

  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()方法无效。 我认为这可能与提交交易有关,但是我已经尝试过类似的操作,但是没有运气。 有任何想法吗?

我发现了这个问题。

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

在delete()之后,我还需要session.flush()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM