0

我发现了奇怪的休眠行为,我无法解释。

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

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

这是我上面描述的代码:

// 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。

4

1 回答 1

0

由于事务隔离,您无法在另一个事务中看到未提交的数据。你在这里有两个不同的事务,所以一个看不到另一个的未提交数据。默认的隔离主义者是读提交的。刷新 dosnt 意味着提交。提交只会在事务结束时完成。因此,当您在第一个事务中刷新数据时,数据会写入 db ,但不会提交,因此事务 2 看不到它。

于 2012-08-04T07:50:20.180 回答