简体   繁体   English

Hibernate不会删除我的对象。 为什么?

[英]Hibernate is not deleting my objects. Why?

I have just set up a test that checks that I am able to insert entries into my database using Hibernate. 我刚刚设置了一个测试,该测试可以检查是否可以使用Hibernate将条目插入数据库。 The thing that drives me crazy is that Hibernate does not actually delete the entries, although it reports that they are gone! 使我发疯的是,尽管它报告它们已消失,但Hibernate实际上并未删除这些条目!

The test below runs successfully, but when I check my DB afterwards the entries that were inserted are still there! 下面的测试成功运行,但是之后我检查数据库时,插入的条目仍然存在! I even try to check it using assert (yes I have -ea as vm parameter). 我什至尝试使用assert来检查它(是的,我将-ea作为vm参数)。 Does anyone have a clue why the entries are not deleted? 有谁知道为什么不删除条目的线索?

public class HibernateExportStatisticDaoIntegrationTest {
    HibernateExportStatisticDao dao;
    Transaction transaction;

    @Before
    public void setUp(){
        assert numberOfStatisticRowsInDB() == 0;
        dao = new HibernateExportStatisticDao(HibernateUtil.getSessionFactory());
    }

    @After
    public void deleteAllEntries(){
        assert numberOfStatisticRowsInDB() != 0;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        for(PersistableStatisticItem item:allStatisticItemsInDB()) {
            session.delete(item);
        }
        session.flush();
        assert numberOfStatisticRowsInDB() == 0;
    }

    @Test public void exportAllSavesEntriesToDatabase(){
        int expectedNumberOfStatistics = 20;
        dao.exportAll(StatisticItemFactory.createTestStatistics(expectedNumberOfStatistics));

        assertEquals(expectedNumberOfStatistics, numberOfStatisticRowsInDB());
    }

    private int numberOfStatisticRowsInDB() {
        return allStatisticItemsInDB().size();
    }

    @SuppressWarnings("unchecked")
    private List<PersistableStatisticItem> allStatisticItemsInDB(){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        transaction = session.beginTransaction();
        Query q = session.createQuery("FROM PersistableStatisticItem item");
        return q.list();
    }
}

The console is filled with 控制台充满了

Hibernate: delete from UPTIME_STATISTICS where logDate=? and serviceId=?

but nothing has been deleted when I check it. 但是当我检查它时,什么都没有被删除。

I guess it's related to inconsistent use of transactions (note that beginTransaction() in allStatisticItemsInDB() is called several times without corresponding commits). 我猜想这与事务使用不一致有关(请注意,多次调用allStatisticItemsInDB()中的beginTransaction()而没有相应的提交)。

Try to manage transactions in proper way, for example, like this: 尝试以适当的方式管理事务,例如,如下所示:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
for(PersistableStatisticItem item:
    session.createQuery("FROM PersistableStatisticItem item").list()) {
    session.delete(item);
}
session.flush();
assert session.createQuery("FROM PersistableStatisticItem item").list().size() == 0;
tx.commit();

See also: 也可以看看:

I have the same problem. 我也有同样的问题。 Although I was not using transaction at all. 尽管我根本没有使用事务。 I was using namedQuery like this : 我正在这样使用namedQuery:

Query query = session.getNamedQuery(EmployeeNQ.DELETE_EMPLOYEES);
int rows = query.executeUpdate();
session.close();

It was returning 2 rows but the database still had all the records. 它返回2行,但是数据库仍然具有所有记录。 Then I wrap up the above code with this : 然后,我用以下代码包装上面的代码:

Transaction transaction = session.beginTransaction();
Query query = session.getNamedQuery(EmployeeNQ.DELETE_EMPLOYEES);
int rows = query.executeUpdate();
transaction.commit();
session.close();

Then it started working fine. 然后它开始正常工作。 I was using SQL server. 我正在使用SQL Server。 But I think if we use h2, above code (without transaction) will also work fine. 但是我认为,如果我们使用h2,则上述代码(无事务处理)也可以正常工作。 One more observation : To insert and get records usage of transaction is not mandatory but for deletion of records we will have to use transaction. 另一点观察:插入和获取记录对事务的使用不是强制性的,但是对于记录的删除,我们将不得不使用事务。 (only tested in SQL server) (仅在SQL Server中测试)

Can you post your DB schema and HBM or Fluent maps? 您可以发布数据库架构和HBM或Fluent映射吗? One thing that got me a while back was I had a ReadOnly() in my Fluent map. 让我回想起一件事的是我的Fluent地图中有一个ReadOnly()。 It never threw an error and I too saw the "delete from blah where blahblah=..." in the logs. 它从未抛出错误,我也看到了日志中的“从blahblah = ...处删除”。

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

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