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?
thanks,
- Ryan
Code:public void testUserNameExists() throws Exception { User user = // retrieve a User from db assertFalse("No userName conflict", dao.userNameExists(user)); user.setUserName("SomeKnownUserName"); assertTrue("userName conflict", dao.userNameExists(user)); }Code: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()) .iterate().next(); } }); return i.intValue() > 0; }


Reply With Quote