Spring JDBC : Integration with Hibernate

It is common to see enterprise Java application using  Spring and Hibernate integration. We will be building on our exsisting  spring jdbc application. I am using MYSQL DB which has a ’employee’ table with test data.
We need to add spring-orm and hibernate denpendecies in pom.xml:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>mynotes.corespring.test</groupId>
 <artifactId>MyNotes_core_spring</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <properties>
 <org.springframework.version>4.0.3.RELEASE</org.springframework.version>
 </properties>
 <dependencies>
 <!-- Core utilities used by other modules. Define this if you use Spring
 Utility APIs (org.springframework.core.*/org.springframework.util.*) -->
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>${org.springframework.version}</version>
 </dependency>

<!-- Bean Factory and JavaBeans utilities (depends on spring-core) Define
 this if you use Spring Bean APIs (org.springframework.beans.*) -->
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-beans</artifactId>
 <version>${org.springframework.version}</version>
 </dependency>

<!-- Application Context (depends on spring-core, spring-expression, spring-aop,
 spring-beans) This is the central artifact for Spring's Dependency Injection
 Container and is generally always defined -->
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>${org.springframework.version}</version>
 </dependency>
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>5.1.26</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-jdbc</artifactId>
 <version>${org.springframework.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-orm</artifactId>
 <version>${org.springframework.version}</version>
 </dependency>
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-core</artifactId>
 <version>4.3.1.Final</version>
 </dependency>

</dependencies>
</project>

Notice the last 2 dependencies. All the related depencies will be automatically be downloaded by maven.
Our Entity class Employee.java


package mynotes.spring.hibernateModel;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Employee{
 @Id
 private int id;
 private String name;
 private String phone;

 @Override
 public String toString() {
 return ("Id=>" + this.id + " Name=>" + this.name+ " phone=>"
 + this.phone);
 }

public int getId() {
 return id;
 }

public void setId(int id) {
 this.id = id;
 }

public String getName() {
 return name;
 }

public void setName(String name) {
 this.name = name;
 }
 public String getPhone() {
 return phone;
 }

public void setPhone(String phone) {
 this.phone = phone;
 }

}

Writing our Dao class MySpringHibernateDao


package mynotes.spring.hibernateMain;

import mynotes.spring.hibernateModel.Employee;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class MySpringHibernateDao {

@Autowired
 private SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
 return sessionFactory;
 }

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

public Employee getEmployeeByid(int id) {
 return (Employee) getSessionFactory().openSession().get(Employee.class,id);

}

}

As you know hibernate needs a SessionFactory object to create sessions and we use this session to run our queries. Usually one application will only have one SessionFactory. We have a private sessionFactory memeber varaible which is autowired. we will create this bean in spring.xml. The getemployeeByid is the method which takes in an int and return the corresponding Employee with that id. This is achieved by opeing the session using sessionFactory and using get() method of hibernate.
Notice the stereotype @Repository over the class. This makes it a bean. Now you can annotate @Component instead and this will work perfectly fine, but by annotating them with @Repository, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts. The @Repository annotation carries with it some additional functionality, it causes exceptions to be wrapped up as DataAccessExceptions.Few stereotype annotation :

@Component – generic stereotype for any Spring-managed component

@Repository – stereotype for persistence layer

@Service – stereotype for service layer

@Controller – stereotype for presentation layer (spring-mvc)

Writing out spring.xml:


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

<context:annotation-config />
<context:component-scan base-package="mynotes.spring.hibernateMain" />

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/javatest" />
<property name="username" value="root" />
<property name="password" value="admin" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="packagesToScan" value="mynotes.spring.hibernateModel" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>

</beans>

Notice the sessionFactoryBean. Since we are using Hibernate 4 , we would be using LocalSessionFactoryBean. The bean is initialised with the datasource. Also we need to tell sessionFactory about our model classes that would use in persistance, therefore we used the property ‘packagesToScan‘. In order to initialise hibernate properties we use the property ‘hibernateProperties‘. All the hibernate properties are spanned by <props> and mentioned as key. Because we are using mysql, we would be using MySQLDialect. The show_sql property is setted as true to print the hibernate generated queries. and hbm2ddl.auto is kept as update so that the exsistig table in DB could be used (without any droping and then creating new).

Tesing using App.java:


package mynotes.spring.hibernateMain;

import mynotes.spring.hibernateModel.Employee;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("/mynotes/spring/hibernateMain/spring.xml");
MySpringHibernateDao mySpringHibernateDao=context.getBean("mySpringHibernateDao",MySpringHibernateDao.class);
Employee employee=mySpringHibernateDao.getEmployeeByid(2);
System.out.println(employee);
}
}

Output:


Hibernate: select employee0_.id as id1_0_0_, employee0_.name as name2_0_0_, employee0_.phone as phone3_0_0_ from Employee employee0_ where employee0_.id=?
Id=>2 Name=>Jane phone=>234567

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: