替代在线程之间共享hibernate会话

时间:2013-05-20 20:49:22

标签: java multithreading spring hibernate spring-transactions

我正在使用Spring 3.0.7 / Hibernate 3.5.0。 我有一些适用于hibernate实体的代码。它工作正常。当我尝试对此代码进行集成测试时,会出现问题。下面是关于交易如何布局代码的方案,只是为了说明问题的内容。

class EntityDAOImpl implements EntityDAO<T>
{
    public T save(T entity)
    {
        getHibernateTemplate().saveOrUpdate(entity);
    }
}
class EntityManagerImpl : implements EntityManager
{
    //EntityDAO dao;
    @Transactional
    public Entity createEntity()
    {
        Entity entity = dao.createNew();
        //set up entity
        dao.save(entity);
    }
    public Entity getFirstEntity()
    {
        return dao.getFirst();
    }
}

代码跨两个线程运行。

Thread1:
    //EntityManager entityManager
    entityManager.createEntity();
    //enity was saved and commited into DB
    Thread thread2 = new Thread();
    thread2.start();
    //...
    thread2.join();
    ...
Thread2:
    //since entity was commited, second thread has no problem reading it here and work with it
    Entity entity = entityDao.findFirst();

现在我还对此代码进行了集成测试。这就是问题所在。此测试的事务是回滚的,因为我不希望在完成后看到数据库中的任何更改。

@TransactionConfiguration(transactionManager="transactionManagerHibernate", defaultRollback=true)
public class SomeTest
{
    @Transactional
    public void test() throws Exception
    {
        //the same piece of code as described above is run here. 
        //but since entityManager.createEntity(); doesn't close transaction, 
        //Thread2 will never find this entity when calling entityDao.findFirst()!!!!!
    }
}

据我所知,在线程之间共享一个hibernate会话并不是一个好主意。 你会建议采用什么方法来处理这种情况?

我的第一个想法是尝试简化并避免线程化 - 但线程帮助我释放内存,否则我将不得不在内存中保存大量数据。

0 个答案:

没有答案
相关问题