Skip to content


Attention Hibernate Nerds

This will be of no interest to you unless you do Hibernate coding.

Let’s say I have an Object, Foo. Foo remains within tomcat’s session object.

I DO NOT want a Hibernate session to stay open with Foo. I *do* want a Hibernate session to open and close at specific times about the object, but I want the object to detach otherwise.

Here is an example with a User object. This is what I *want* to happen.

1) User logs in.
1a) Hibernate does the lookup user by name thing, finds a User object (u), creates it.
1b) User object (u) is returned. Hibernate session associated with that User object (u) is closed. User object (u) is now detached.

2) User changes his email address. Clicks “save changes”. This changes a field on the User object (u).
2a) Hibernate opens a Session and does a save on the User object (u).
2b) Hibernate session associated with that User object (u) is closed. User object (u) is now detached. (again).

Basically what I’m trying to do is to grab objects and hold them in ram *WITHOUT* keeping a database connection open.

The docs do not really explain how to do this – to disconnect an Object from its associated Hibernate Session.

Code snippets would be appreciated.

Posted in Tech. Tagged with .


2 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. tague says

    In Yur Hibernate, Saving Yur Detached Objects

    So if I do:

            // setup the dbSession Factory and Transactions
            factory = (SessionFactory)tmp.getBean("dbSessionFactory");
            Session sess = factory.openSession();
            TransactionSynchronizationManager.bindResource(factory,
                                                           new SessionHolder(sess));
            TransactionSynchronizationManager.initSynchronization();
    
            // Setup a security context running as system user
            User sys = (User)sess.get(User.class, new Long(1));
            ThreadLocalSecurityContextHolderStrategy gCtx =
                new ThreadLocalSecurityContextHolderStrategy();
            SecurityContextImpl impl = new SecurityContextImpl();
            UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(sys, "password");
    
            impl.setAuthentication(token);
            gCtx.setContext(impl);
    

    Which shoves a user into the thread-local security context (which is the moral equivalent of what you’re doing)

    Then in a later spot:

            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            User u = (User)auth.getPrincipal();
            u.setEmail("devnul@yurmom.org");
    
            try {
                SessionFactory factory = (SessionFactory)getBean("dbSessionFactory");
                Session sess = factory.openSession();
                Transaction txn = sess.beginTransaction();
                sess.update(u);
                txn.commit();
                sess.close();
            } finally {
                // error handling
            }
        }
    

    The detached object gets persisted to the database without a problem. Is there a particular problem you’re having that makes this not work?

    As a longer term design patter, you might want to reconsider using the same object (User) to represent your database mapping and your Principal. Instead, you might want to have a separate UserPrincipal that has all of the information you need to manage permissions and map back to a user, then have a separate user object that handles things like email. What you decide to do here matters as far as consistency and concurrency and all the pain in the ass stuff.

    Hit me up tonight, I should be online.

  2. nihilus says

    tague above shows how to use a detached obeject, which is basically what you want I think? The update and merge methods on Session allow you to use a detached object. You might need to deal with optimistic locking or such though.

    I don’t have much direct experience with it as all the transaction/session stuff for me is wrapped in Spring AOP.



Some HTML is OK

or, reply to this post via trackback.