Tom
Tom

Reputation: 3176

Hibernate DAO/SessionFactory Use

In my application I have a DAO bean which I inject with a Hibernate sessionFactory (with c3p0 connection pool configured) via Spring. My sessionFactory bean is defined like so:

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
...
</bean>

What is best practice and/or best performance for using the wrapping DAO bean in a threaded environment? Should I define it as a singleton bean and let it get shared between threads while relying on the thread-safeness of the sessionFactory? Or should I create a separate DAO instance for each thread? Does it even matter?

Upvotes: 0

Views: 764

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280175

If your DAOs don't have any member fields other than the SessionFactory, use each as a Singleton passed to all threads.

A common practice with Spring is to annotate your DAO implementation with @Repository and @Autowired the instance into your service or other classes that need to use it.

The SessionFactory#openSession() and SessionFactory#getCurrentSession() return a new Session instance and a thread-local Session, respectively, so nothing is shared across Threads.

Upvotes: 3

Related Questions