Reputation: 3736
I'm here for a bit of advice. I'm using Hibernate with Java. I've implemented a controller interface to distance the User interface from the actual communication with the database. For the given interface I've implemented a database controller class that does the actual communication. This is fed to the user interface by a static controller factory.
Now I discover that the Hibernate doesn't actually load everything I want into the memory. For each controller method call I'm always opening session, doing my stuff, closing the session. Therefore when I try to access my object structure I'm prompted with error that
could not initialize proxy - no Session
With little effort and googling I concluded that the object to which my active object is referencing is not in the memory.
Now I have an option to keep the session open from the moment I start using my objects to the end. But it seems a bit redundant and energy inefficient. I guess I won't lose much by keeping the session open, but I kind of intended to keep the user interface purely out oh the database business. Having my controller interface to have a "tearDown" (and "setUp") method for the user interface seems a bit against given logic.
Upvotes: 0
Views: 1727
Reputation: 5303
When you use lazy loading - that is quite often the default case in Hibernate - you can't have access to unloaded instances after the session is closed.
For example, you have a parent table and a child table, which is mapped in a 1:n relation (In the mapping file or as an annotation). Then you do like this:
1) open session
2) load parent
3) close session
4) call parent.getChild() (or sth. like this)
Then in step 4) you'll get an error message, because Hibernate didn't load the item before, it wants to do now (lazy loading), but it can't, because the session already is close.
If you want to close the session, make sure all necessary data already is loaded. For example if you had done step 4) before step 3) in that example, then it would have worked, and after closing the session you even could access that child again, because it already would be loaded. But you wouldn't be able to store it in the database later, because of the closed session.
Upvotes: 1
Reputation: 6140
I don't understand. You can load entity objects from db and use them after closing session. The objects states will be detached then. You will have to possibly to reattach them to session sometimes to synchronize theirs states with db.
Upvotes: 0