Announcement Announcement Module
No announcement yet.
Hibernate, stop flushing Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Hibernate, stop flushing

    I'm still wrapping my head around FlushMode and other finer points of Hibernate, but I can't seem to figure out how this situation is handled.

    I need to test whether a User.userName is in use by another User. My test case and DAO implementation are below.

    I'm setting the User.userName property, then doing a query looking for another user with that same name. The problem is, before running the query, Hibernate flushes the session, saving the bad userName and causing a constraint violation.

    The obvious and easy solution would be to not actually set the userName until it's known to be good.. but doesn't this go against the whole point of using domain objects all the way down to your forms?

    I tried setting session.flushMode to NEVER both inside the HibernateCallback and when opening the session originally but neither seemed to work.

    What is the proper way to handle this situation?

    - Ryan

        public void testUserNameExists() throws Exception {
            User user = // retrieve a User from db
            assertFalse("No userName conflict", dao.userNameExists(user));
            assertTrue("userName conflict", dao.userNameExists(user));
        public boolean userNameExists(final User user) throws DataAccessException {
            Integer i = (Integer) getHibernateTemplate().execute(new HibernateCallback() {
    			public Object doInHibernate(Session session) throws HibernateException {
    				// Session flushes here, before doing query
    				return session.createQuery(
    				        "select count(*) from User as u where u!=:user and u.userName=:name")
    				        .setEntity("user", user)
    				        .setString("name", user.getUserName())
            return i.intValue() > 0;

  • #2
    Hmm, guess I missed something before. It works now, I just needed to clear the session before that known bad value was flushed.

    However, my question still stands... What's the proper way to handle this situation in my application? Should I give my DAO interface a clear() method? Any thoughts are much appreciated.