Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 994
glaz666 Avatar asked Oct 28 '10 09:10

glaz666


People also ask

What is default flush mode in Hibernate?

AUTO. The Session is sometimes flushed before query execution in order to ensure that queries never return stale state. This is the default flush mode.

Does Hibernate flush commit?

flush() will synchronize your database with the current state of object/objects held in the memory but it does not commit the transaction. So, if you get any exception after flush() is called, then the transaction will be rolled back.

When should I flush my Hibernate session?

By default, Hibernate uses the AUTO flush mode which triggers a flush in the following circumstances: prior to committing a Transaction. prior to executing a JPQL/HQL query that overlaps with the queued entity actions. before executing any native SQL query that has no registered synchronization.


1 Answers

Try adding the following:

@Autowired
private SessionFactory sessionFactory;

@Before
public void myInitMethod(){
  sessionFactory.getCurrentSession().setFlushMode(FlushMode.ALWAYS);
}
like image 130
Ed J Avatar answered Sep 18 '22 22:09

Ed J