Hibernate doesn’t fetch collections within a bean in the same session the beans were created in. If you need objects in those collections later on within that session, you had better put them in there. This even holds true when you go back to hibernate to refetch the same object instance. Here’s a quick example:
User user = new User("Brian", "Pontarelli"); userDAO.saveOrUpdate(user); Role role = new Role(); role.setUser(user); roleDAO.saveOrUpdate(role); user = userDAO.fetch("Brian", "Pontarelli"); user.getRoles().get(0); // THIS IS NULL!
Once the session is closed out and the fetch is performed in a new session then this will work fine. I can see how this behavior protects the object instance somewhat, but this means that the instance also misses any updates within other threads to its associations. This I haven’t tested because it is a severe pain in the ass, but I’ll probably give it a try tomorrow.
As a quick closing thought, all this ORM stuff in Java seems like such a pain compared to Rails and ActiveRecord. I can understand that transactions can be quite powerful and the POJO model is powerful, but I’m not convinced that this truly makes life that much better as compared to what you gain from a dynamic language’s ability to handle all of the mapping internally and on the fly while making the class look like a simple data holder.