aspose file tools*
The moose likes Object Relational Mapping and the fly likes Design question for creating a DAO using Hibernate Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Design question for creating a DAO using Hibernate" Watch "Design question for creating a DAO using Hibernate" New topic
Author

Design question for creating a DAO using Hibernate

Sammy Bill
Ranch Hand

Joined: Dec 29, 2008
Posts: 96
Hello,

I m creating a DAO using Hibernate.
is it a good idea to create SessionFactory, Session and Transaction Objects as instance fields and initialize them in the Constructor?
should i close the session on every method that interact with the DB?
if not can you suggest a better design?

Thanks
Javid Jamae
Author
Ranch Hand

Joined: May 14, 2008
Posts: 198
No, keep the SessionFactory in a singleton, then get the session using sessionFactory.getCurrentSession() to get the current session for the thread that you're in.

Read the first chapter of the Hibernate documentation.

The transaction boundaries depend on how long your transactions are. Typically you manage one per request. In a Web-based app, you might start and end the transaction in a ServletFilter.


Author: JBoss in Action, javidjamae.com, @javidjamae on Twitter
Sammy Bill
Ranch Hand

Joined: Dec 29, 2008
Posts: 96
Javid Jamae wrote:No, keep the SessionFactory in a singleton, then get the session using sessionFactory.getCurrentSession() to get the current session for the thread that you're in.

Read the first chapter of the Hibernate documentation.

The transaction boundaries depend on how long your transactions are. Typically you manage one per request. In a Web-based app, you might start and end the transaction in a ServletFilter.


Thanks for your Help.
So you mean, get a new session instance from the sessionFactory and a new transaction from the session in every method and i dont need to close them untill i actually use the DAO in a servlet or so??

bsically thats what i have:


Please correct me if i m doing anything wrong.

Thanks again.
Benjamin Winterberg
Ranch Hand

Joined: Sep 19, 2007
Posts: 36
You should take a look at the Open Session In View pattern: http://www.hibernate.org/43.html


Hibernate DAOs with Spring | Separation of Concerns | Eclipse Code Templates | more...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Design question for creating a DAO using Hibernate