About 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.

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.

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.

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.

The Maven project structure is shown below:

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:

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.

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.

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.

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.

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.

Newsletter

Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

Email address:

Receive Java & Developer job alerts in your Area

Leave this field empty if you're human:

Join Us

With 1,240,600 monthly unique visitors and over 500 authors we are placed among the top Java related sites around. Constantly being on the lookout for partners; we encourage you to join us. So If you have a blog with unique and interesting content then you should check out our JCG partners program. You can also be a guest writer for Java Code Geeks and hone your writing skills!

Disclaimer

All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners. Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries. Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.