开发者

Set Hibernate session's flush mode in Spring

I am writing integration tests and in one test method I'd like to write some data to DB and then read it.

@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 storing and reading data, the session should be flushed because the default FushMode is AUTO thus no data can be actually stored in DB.

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

All DB calls in DAO goes with HibernateTemplate instance.

Thanks in advance.


Try adding the following:

@Autowired
private SessionFactory sessionFactory;

@Before
public void myInitMethod(){
  sessionFactory.getCurrentSession().setFlushMode(FlushMode.ALWAYS);
}


This should be sufficient:

@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>

View the source of TransactionalTestExecutionListener if you have questions about how transactions work in this scenario.

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


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

  • before some query executions
  • from org.hibernate.Transaction.commit()
  • from Session.flush()

Therefore, before dummyDAO.findAll().size(); is called, objects in session are already flushed in db. Setting FlushMode to ALWAYS is not necessary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜