休眠。在主线程中创建的实体在子项1中不可见

时间:2012-08-03 15:59:11

标签: multithreading hibernate transactions

我发现了奇怪的hibernate行为,我无法解释它。

如果我在事务中的默认线程中创建一个对象并进行手动刷新 然后我在其他帖子中找不到它。

如果我在一个具有相同条件的特殊线程中创建一个对象,那么一切都很好。

以下是我上面描述的代码:

// transaction template with propagation required 
            ttNew.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    Assert.assertEquals(envStDao.getAll().size(), 0);
                    g = new Group();
                    g.setDescription("trial");
                       // in debugger I get id = 1
                    groupDao.save(g);

                    groupDao.flush();
                    accDao.flush();


                 }
                });

    // second stage right after the first - searching the group

   Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
        ttNew.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
            // here I get NULL!
            Group gg = groupDao.get(1);
        }
    });
        }
    });
    t2.start();
    t2.join();

如果我将代码的第一个块包装到线程中,就像以前我得到的那样。

有什么想法吗?

我在junit测试中运行上面的代码。 Dao对象使用HibernateTemplate。

1 个答案:

答案 0 :(得分:0)

由于transaction isolation,您无法在其他交易中看到未提交的数据。你在这里有两个不同的交易,因此无法看到另一个的未提交数据。 读取提交的默认隔离列表。 flush dosnt意味着提交。提交只在交易结束时完成。因此,当您在第一个事务中刷新数据时,数据将写入数据库,但不会提交,因此事务2无法看到它。