Monday, 22 October 2012

Hibernate 4 Spring 3 and SessionFactory

Spring 3.1 and Hibernate configuration. Since hibernate template is now deprecated you must get the session using

However this gets a new session each time. Alternatively you can use

This will likely give you an session not found error (or something along those lines), if hibernate isn't configured correctly.

So add the following to your session factory.

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="hibernateProperties">
<!-- Fixes the no session found bug -->
<prop key="hibernate.current_session_context_class">

This will allow spring to manage the session context.

That will work aslong as there is a transaction available. If a transaction manager is configured in spring, then you can use @Transaction over methods accessing the db.

Other possible values for the hibernate.current_session_context_class are "thread", "jta", or "managed". See here.

If you want more controls over transactions then you can manually begin and close transactions. Bigger transactions can potentially speed up your applications. Transactions can span multiple methods.
Session session = sessionFactory.getCurrentSession();
//code here

1 comment:

  1. The effectiveness of IEEE Project Domains depends very much on the situation in which they are applied. In order to further improve IEEE Final Year Project Domains practices we need to explicitly describe and utilise our knowledge about software domains of software engineering Final Year Project Domains for CSE technologies. This paper suggests a modelling formalism for supporting systematic reuse of software engineering technologies during planning of software projects and improvement programmes in Final Year Project Centers in Chennai.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai