Thursday, 3 April 2014

HibernateTemplate not advised starting Hibernate 4


Here is the simple example for spring and hibernate integration
 spring_hibernate.zip

The sessionFactory is injected into the DAO with all definitions in the beans.xml with datasource wired.



beans.xml 

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean name="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver" />
        <property name="url" value="jdbc:hsqldb:hsql://localhost/section1" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>

    <bean name="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="packagesToScan" value="org.entity"/>
    </bean>


    <bean name="EmployeeDAO" class="org.dao.EmployeeDAO">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

</beans>
 

org.entity.Employee

package org.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Employee {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Integer employeeId;
 private String firstName;
 private String lastName;
 private String jobTitle;
 private Double salary;

..............
..............
}


DAO

 
 

package org.dao;

import org.entity.Employee;
import org.hibernate.SessionFactory;

public class EmployeeDAO {

 private SessionFactory sessionFactory;

 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }

 public void getEmployee() throws Exception {
  try {
   Employee emp = (Employee) sessionFactory.openSession().get(Employee.class, 1);
   System.out.println("--sessionFactory.get(Employee.class, 1)   ---> " + emp);

  } catch (Exception e) {
   e.printStackTrace();
   throw e;
  }

 }
}


Test Code

package org;

import org.dao.EmployeeDAO;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmployeeDAOTest {

 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
 
 @Test
 public void testGetEmployeeWithHibernate() throws Exception{
 
  EmployeeDAO dao = (EmployeeDAO) ctx.getBean("EmployeeDAO");
  dao.getEmployee();
 }

}
 

2 comments: