Monday, 9 June 2014

Spring MVC + Hibernate DB Configuration

step1:

Create a datasource

Declare a bean and its class and inject all its properties like driver class name,url,username and password

ClassName:DriverManagerDataSource

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>

Steps 2:
ClassName:AnnotationSessionFactoryBean
Create a session factory based on AnnotationSessionFactoryBean java class.
Inject its all dependent properties such as datasource and hibernate properties file.

<bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>com.dineshonjava.model.Employee</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
    <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
   </props>
  </property>
 </bean>

Step 3:

Create hibernate transaction manager bean and inject dependent session factory to it.
 ClassName:HibernateTransactionManager 


<bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>


Need of HibernateTransactionManager :

Hibernate transaction manager:

See below code snippet for completing simple transaction. Here in order to execute simple code we are plumbing code like closing/opening connections, exception handling etc. This small unit of work usually called transaction can be handled by annoting the method with @Transactional that’s it hibernate will take care of transaction details.

public void doSomething()

{

Session sess = factory.openSession();

Transaction tx = null;

try

{   

         tx = sess.beginTransaction();// do some work... tx.commit();

}

  catch (RuntimeException e)

{

if (tx != null) tx.rollback();throw e; // or display error message

}

finally

{

sess.close();

}

}

After making use of transactional manager:

@Transactional

public void doSomething() {

    // do some work

}











 


No comments:

Post a Comment