Results 1 to 2 of 2

Thread: Hibernate, stop flushing

  1. #1
    Join Date
    Sep 2004
    Posts
    11

    Default 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?

    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;
        }

  2. #2
    Join Date
    Sep 2004
    Posts
    11

    Default

    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.

Similar Threads

  1. Replies: 5
    Last Post: Dec 27th, 2005, 07:00 AM
  2. Replies: 4
    Last Post: Oct 19th, 2005, 03:39 PM
  3. Loosing my SecureContext
    By sklakken in forum Security
    Replies: 3
    Last Post: Jul 21st, 2005, 01:44 PM
  4. Replies: 3
    Last Post: Nov 19th, 2004, 07:16 PM
  5. Replies: 7
    Last Post: Aug 21st, 2004, 03:42 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •