JPA/ORM

Spring Hibernate Integration Example – Mysql and Maven Showcase

In this tutorial we shall show you how to create a simple Spring Hibernate MySql example. The Spring Framework supports integration with Hibernate for resource management, data access object (DAO) implementations and transaction strategies. Here we are using a simple Entity class that is mapped to a database table and we implement the basic CRUD (create- retrieve- update- delete) functionality to the database.

Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using Spring version 3.2.3 and the JDK 7_u_21. The Hibernate version is 4.1.9, and the database used in the example is MySQL Database Server 5.6.

Let’s begin.

1. Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

New-Maven-Project

In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is checked, hit “Next” to continue with default values.

Maven-Project-Name-Location

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. We will set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to "springexample". The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample" and the project name as "springexample". Hit “Finish” to exit the wizard and to create your project.

Configure-Maven-Project

The Maven project structure is shown below:

Maven-project-structure

    It consists of the following folders:

  • /src/main/java folder, that contains source files for the dynamic content of the application,
  • /src/test/java folder contains all source files for unit tests,
  • /src/main/resources folder contains configurations files,
  • /target folder contains the compiled and packaged deliverables,
  • the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

2. Add Spring 3.2.3 dependency

  • Locate the “Properties” section at the “Overview” page of the POM editor and perform the following changes:
    Create a new property with name org.springframework.version and value 3.2.3.RELEASE.
  • Navigate to the “Dependencies” page of the POM editor and create the following dependencies (you should fill the “GroupId”, “Artifact Id” and “Version” fields of the “Dependency Details” section at that page):
    Group Id : org.springframework Artifact Id : spring-web Version : ${org.springframework.version}

Alternatively, you can add the Spring dependencies in Maven’s pom.xml file, by directly editing it at the “Pom.xml” page of the POM editor, as shown below:
 
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>com.javacodegeeks.snippets.enterprise</groupId>
	<artifactId>springexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
	</dependencies>

	<properties>
		<spring.version>3.2.3.RELEASE</spring.version>
	</properties>
</project>

As you can see Maven manages library dependencies declaratively. A local repository is created (by default under {user_home}/.m2 folder) and all required libraries are downloaded and placed there from public repositories. Furthermore intra – library dependencies are automatically resolved and manipulated.

3. Add Hibernate and MySql dependencies

The Hibernate and MySql-connector dependencies are added, along with the org.apache.commons.dbcp package, that provides database Connection Pool API. We also need the spring-orm package and the javax.persistence api.

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>com.javacodegeeks.snippets.enterprise</groupId>
	<artifactId>springexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.2.2</version>
		</dependency>

		<dependency>
			<groupId>javax.persistence</groupId>
			<artifactId>persistence-api</artifactId>
			<version>1.0</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.1.9.Final</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.6</version>
		</dependency>

	</dependencies>
	<properties>
		<spring.version>3.2.3.RELEASE</spring.version>
	</properties>
</project>

4. The entity class

Employee.java class is a class with three properties. It uses the javax.persistence annotations to be mapped to a table, EMPLOYEE in the database. In particular, the @Entity annotation specifies that the class is an entity. The @Table annotation specifies the primary table for the annotated entity. The @Column annotation is used to specify a mapped column for the persistent field, whereas the @Id annotation specifies the primary key field of the entity.

Employee.java

package com.javacodegeeks.snippets.enterprise.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "EMPLOYEE")
public class Employee {

	@Id
	@Column(name = "ID", nullable = false)
	private String id;

	@Column(name = "NAME", nullable = false)
	private String name;

	@Column(name = "AGE", nullable = false)
	private long age;
	
	public Employee() {
	}

	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public long getAge() {
		return age;
	}

	public void setAge(long age) {
		this.age = age;
	}

}

5. The DAO class

The Data Access Object implemented to interact with the database uses Hibernate data access technology. It is the EmployeeDAOImpl.java class. It uses the @Repository annotation, to guarantee that the Data Access Object (DAO) provides exception translation. When using Hibernate, we must decide how to handle the native exception classes. The DAO throws a subclass of a HibernateException, that is a run-time exception and does not have to be declared or caught. We may also deal with IllegalArgumentException and IllegalStateException. This means that callers can only treat exceptions as generally fatal, unless they want to depend on Hibernate’s own exception structure. Spring enables exception translation to be applied transparently through the @Repository annotation.

The DAO uses the Hibernate SessionFactory that provides Sessions to access the Database. It gets it as bean reference from the Spring IoC container. All the methods implemented in the DAO get Session instances by using the getCurrentSession() method of SessionFactory. The SessionFactory is injected using the @Autowire annotation.

The basic CRUD methods implemented here use the persist(Object object), get(Class clazz, Serializable id), update(Object object) and delete(Object object) API methods of Session to create, retrieve, update and delete an object from the database.

EmployeeDAOImpl.java

package com.javacodegeeks.snippets.enterprise.dao;

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

import com.javacodegeeks.snippets.enterprise.model.Employee;

@Repository("employeeDAO")
public class EmployeeDAOImpl implements EmployeeDAO {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public void persistEmployee(Employee employee) {
		sessionFactory.getCurrentSession().persist(employee);
	}

	@Override
	public Employee findEmployeeById(String id) {
		return (Employee) sessionFactory.getCurrentSession().get(Employee.class, id);
	}

	@Override
	public void updateEmployee(Employee employee) {
		sessionFactory.getCurrentSession().update(employee);

	}
	@Override
	public void deleteEmployee(Employee employee) {
		sessionFactory.getCurrentSession().delete(employee);

	}

}

The inteface of EmployeeDAOImpl.java is shown below:

EmployeeDAO.java

package com.javacodegeeks.snippets.enterprise.dao;

import com.javacodegeeks.snippets.enterprise.model.Employee;

public interface EmployeeDAO {
	
		  void persistEmployee(Employee employee);
		  
		  Employee findEmployeeById(String id);
		  
		  void updateEmployee(Employee employee);
		  
		  void deleteEmployee(Employee employee);
		  
}

6. The Service class

The EmployeeDAOImpl.java class is injected in the EmployeeServiceImpl.java class. Thus, in the methods implemented here, the DAO methods are invoked to perform the basic interaction with the database. The EmployeeServiceImpl.java class is annotated with the @Service annotation, dictating that it is a Spring Bean and thus allowing Spring to auto-detect it.

The @Transactional annotation is placed before the methods, to denote that a transaction is created when each method is invoked. The transaction will be configured in Spring configuration file.

EmployeeServiceImpl.java

package com.javacodegeeks.snippets.enterprise.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.javacodegeeks.snippets.enterprise.dao.EmployeeDAO;
import com.javacodegeeks.snippets.enterprise.model.Employee;

@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService{

	@Autowired
	EmployeeDAO employeeDAO;
	
	@Override
	@Transactional
	public void persistEmployee(Employee employee) {
		employeeDAO.persistEmployee(employee);
		
	}

	@Override
	@Transactional
	public void updateEmployee(Employee employee) {
		employeeDAO.updateEmployee(employee);
		
	}
	@Override
	@Transactional
	public Employee findEmployeeById(String id) {
		return employeeDAO.findEmployeeById(id);
	}

	@Override
	@Transactional
	public void deleteEmployee(Employee employee) {
		employeeDAO.deleteEmployee(employee);
		
	}

}

The interface of EmployeeServiceImpl.java class is shown below:

EmployeeService.java

package com.javacodegeeks.snippets.enterprise.service;

import com.javacodegeeks.snippets.enterprise.model.Employee;

public interface EmployeeService {

	void persistEmployee(Employee employee);

	Employee findEmployeeById(String id);

	void updateEmployee(Employee employee);

	void deleteEmployee(Employee employee);
}

7. Configure Spring Beans

The applicationContext.xml file shown below defines and configures all the beans needed for the interaction with the database.

First of all, since we are using Spring beans, we must use the <context:component-scan> element to define where the beans are, so that the IOC container will detect them.

We also use the <tx:annotation-driven/> element, so that Spring is @Transactional-aware and can detect the @Transactional annotations to configure the appropriate beans with transactional behavior.

In the datasource bean the DataSource is defined. Spring obtains a connection to the database through a DataSource. The properties to be configured here are the driverClassName, the url to the database and the username and password for the connection to the database.

In the sessionFactory bean we must define the SessionFactory class. The SessionFactory class is a thread-safe object that is instantiated once to serve the entire application. The SessionFactory is used to create Sessions. A Session is used to get a physical connection with a database. The Session object is instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.

The class that implements the sessionFactory is the org.springframework.orm.hibernate4.LocalSessionFactoryBean class. We can configure the properties this class provides in the bean definition. In the datasource property, that is a reference to the DataSource we set the DataSource to be used by the SessionFactory. In the annotatedClasses property we must specify annotated entity classes to register with this Hibernate SessionFactory. The Employee class is the value of this property. The org.springframework.orm.hibernate4.LocalSessionFactoryBean class also provides a hibernateProperties property to configure. Here we can configure all properties provided by Hibernate. For example, JDBC Properties, Hibernate Configuration Properties, Cache and Transaction Properties and SQL dialects. Here we have set two properties. The hibernate.dialect property is set to MySql, and the hibernate.show_sql is set to true so that the queries implemented are printed.

Last but not least, the transactionManager bean is defined. The class to implement the transaction is the org.springframework.orm.hibernate4.HibernateTransactionManager. The bean has a property named sessionFactory, whose value is a reference to the sessionFactory bean.

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 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 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

  <context:component-scan base-package="com.javacodegeeks.snippets.enterprise.*" />
    
  <tx:annotation-driven/>
  
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/test" />
    <property name="username" value="root" />
    <property name="password" value="root" />
  </bean>

  <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
     <property name="annotatedClasses">
            <list>
                <value>com.javacodegeeks.snippets.enterprise.model.Employee</value>
            </list>
        </property>
    <property name="hibernateProperties">
      <props>
        <prop 
         key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
        <prop key="hibernate.show_sql">true</prop>
      </props>
    </property>
  </bean>
  
  <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" 
    p:sessionFactory-ref="sessionFactory">
  </bean>
</beans>

8. Run the Application

In App.java class we load the applicationContext.xml file. We create an Employee object and use the CRUD methods to interact with the database.

App.java

package com.javacodegeeks.snippets.enterprise;

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

import com.javacodegeeks.snippets.enterprise.model.Employee;
import com.javacodegeeks.snippets.enterprise.service.EmployeeService;

public class App {

	public static void main(String[] args) {
		System.out.println("load context");
		ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		Employee em = new Employee();
		em.setId("123");
		em.setName("John");
		em.setAge(35);
		EmployeeService emService = (EmployeeService) context.getBean("employeeService");
		emService.persistEmployee(em);
		System.out.println("Updated age :" + emService.findEmployeeById("123").getAge());		
		em.setAge(32);
		emService.updateEmployee(em);
		System.out.println("Updated age :" + emService.findEmployeeById("123").getAge());
		emService.deleteEmployee(em);
		context.close();
	}

}

When you run the application, you will see the sql queries in the output. You will also see the the age of the first emloyee and the age of the updated employee.

Output


Hibernate: insert into EMPLOYEE (AGE, NAME, ID) values (?, ?, ?)
Hibernate: select employee0_.ID as ID0_0_, employee0_.AGE as AGE0_0_, employee0_.NAME as NAME0_0_ from EMPLOYEE employee0_ where employee0_.ID=?
Persisted age :35
Hibernate: update EMPLOYEE set AGE=?, NAME=? where ID=?
Hibernate: select employee0_.ID as ID0_0_, employee0_.AGE as AGE0_0_, employee0_.NAME as NAME0_0_ from EMPLOYEE employee0_ where employee0_.ID=?
Updated age :32
Hibernate: select employee_.ID, employee_.AGE as AGE0_, employee_.NAME as NAME0_ from EMPLOYEE employee_ where employee_.ID=?
Hibernate: delete from EMPLOYEE where ID=?

 
This was an example of Spring Hibernate and Mysql integration.
Download the Eclipse project of this tutorial : SpringHibernateMysqlMavenExample.zip

Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mishu
Mishu
5 years ago

while executing above application it says: “No bean named ’employeeService’ is defined”.
Kindly help !

Sid
Sid
4 years ago
Reply to  Mishu

You can add a @Component or @Bean to the employeeService class, to wire it as a bean.

Back to top button