Set Hibernate Session Cleanup Mode in Spring

I write integration tests, and in one testing method I would like to write some data in the database, and then read them.

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) @TransactionConfiguration() @Transactional public class SimpleIntegrationTest { @Resource private DummyDAO dummyDAO; /** * Tries to store {@link com.example.server.entity.DummyEntity}. */ @Test public void testPersistTestEntity() { int countBefore = dummyDAO.findAll().size(); DummyEntity dummyEntity = new DummyEntity(); dummyDAO.makePersistent(dummyEntity); //HERE SHOULD COME SESSION.FLUSH() int countAfter = dummyDAO.findAll().size(); assertEquals(countBefore + 1, countAfter); } } 

As you can see between saving and reading data, the session should be reset, because by default FushMode is AUTO , therefore data cannot be actually stored in the database.

Question: Can I specify how to set FlushMode to ALWAYS in a factory session or somewhere else to avoid repeating the call to session.flush() ?

All DB calls in the DAO come with an instance of HibernateTemplate .

Thanks in advance.

+6
spring hibernate spring-3
source share
3 answers

Try adding the following:

 @Autowired private SessionFactory sessionFactory; @Before public void myInitMethod(){ sessionFactory.getCurrentSession().setFlushMode(FlushMode.ALWAYS); } 
+1
source share

According to the hibernate sleeping object , flushing occurs by default at the following points:

  • before making requests
  • from org.hibernate.Transaction.commit ()
  • from Session.flush ()

Therefore, before calling dummyDAO.findAll().size(); , objects in the session are already dumped in db. Installing FlushMode in ALWAYS is not required.

+1
source share

That should be enough:

 @ContextConfiguration(locations="classpath:applicationContext.xml") public class SimpleIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired(required = true) private DummyDAO dummyDAO; @Test public void testPersistTestEntity() { assertEquals(0, dummyDAO.findAll().size()); dummyDAO.makePersistent(new DummyEntity()); assertEquals(1, dummyDAO.findAll().size()); } } 

From applicationContext.xml

 <bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> 

Check out the TransactionalTestExecutionListener source if you have questions about how transactions work in this scenario.

You can also use AOP (aspect-oriented programming) for proxy transactions.

0
source share

All Articles