我正在使用 Spring 3.0.7 / Hibernate 3.5.0。我有一些适用于休眠实体的代码。它工作正常。当我尝试对此代码进行集成测试时,就会出现问题。下面是有关事务的代码布局方案,只是为了说明问题的含义。
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();
}
}
代码跨 2 个线程运行。
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()!!!!!
}
}
我知道在线程之间共享休眠会话不是一个好主意。你会推荐什么方法来处理这种情况?
我的第一个想法是尝试简化并避免线程化——但线程化可以帮助我清理内存,否则我将不得不在内存中保存大量数据。