Spring Boot + Hibernate 5 + Mysql Example

By Dhiraj Ray, 13 March,2017   7255

This article is about integrating spring boot with hibernate. Here, we will be using spring boot 1.5.1 and hence by default it will be hibernate 5 configurations. We will be creating sample spring boot hibernate example having some rest endpoints exposed through spring controller. The dao class will have sessionFactory injected which will be used to create hibernate session and connect to database. We will be using mysql database.

Lets get started by defining our project structure first.

Project Structure

Following is the project structure. We have controllers, service and dao layers. We have application.properties defined that contains configurations related to our datasource.

spring-boot-hibernate-project-strct

Maven Dependencies

spring-boot-starter-parent: It provides useful Maven defaults. It also provides a dependency-management section so that you can omit version tags for existing dependencies.

spring-boot-starter-web: It includes all the dependencies required to create a web app. This will avoid lining up different spring common project versions.

spring-boot-starter-tomcat: It enable an embedded Apache Tomcat 7 instance, by default.This can be also marked as provided if you wish to deploy the war to any other standalone tomcat.

spring-boot-starter-data-jpa: It provides key dependencies for Hibernate, Spring Data JPA and Spring ORM.

pom.xml
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <exclusions> <exclusion> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> </dependency> </dependencies>

Defining Spring Application class

@SpringBootApplication enables many defaults. It is a convenience annotation that adds @Configuration, @EnableAutoConfiguration, @EnableWebMvc, @ComponentScan

The main() method uses Spring Boot SpringApplication.run() method to launch an application.

Application.java
package com.devglan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

Datasource Configurations in Spring Boot

The most convenient way to define datasource parameters in spring boot application is to make use of application.properties file. Following is our sample application.properties. Here we are using JPA based configurations and hibernate as a JPA provider.

spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

Defining Spring Bean Configs

Spring boot focusses on using JPA to persist data in relational db and it has ability to create repository implementations automatically, at runtime, from a repository interface. But here we are trying to use hibernate as a JPA provider. Hence, following configuration is required to autowire sessionFactory in our DAO class.

BeanConfig.java
package com.devglan; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.persistence.EntityManagerFactory; @Configuration public class BeanConfig { @Autowired private EntityManagerFactory entityManagerFactory; @Bean public SessionFactory getSessionFactory() { if (entityManagerFactory.unwrap(SessionFactory.class) == null) { throw new NullPointerException("factory is not a hibernate factory"); } return entityManagerFactory.unwrap(SessionFactory.class); } }

Hibernate Entity Class

Following is the entity class. The class is annotated as hibernate entity.

UserDetails.java
package com.devglan.model; @Entity @Table public class UserDetails { @Id @Column @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column private String firstName; @Column private String lastName; @Column private String email; @Column private String password; //getters and setters goes here

Defining Spring Controller

Let us define our controller. It has one url mapping that intercepts request at /list and returns all users present in db.

UserController.java
package com.devglan.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.devglan.model.UserDetails; import com.devglan.service.UserService; @Controller public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/list", method = RequestMethod.GET) public ResponseEntity> userDetails() { List userDetails = userService.getUserDetails(); return new ResponseEntity>(userDetails, HttpStatus.OK); } }

Defining Service Class

UserServiceImpl.java
package com.devglan.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.devglan.dao.UserDao; import com.devglan.model.UserDetails; import com.devglan.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public List getUserDetails() { return userDao.getUserDetails(); } }

Defining Dao Implementation

Let us define the dao.

UserDaoImpl.java
package com.devglan.dao.impl; import java.util.List; import org.hibernate.Criteria; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.devglan.dao.UserDao; import com.devglan.model.UserDetails; @Component public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; public List getUserDetails() { Criteria criteria = sessionFactory.openSession().createCriteria(UserDetails.class); return criteria.list(); } }
Note:

We can also get hibernate session in following way using JPA entitymanager. But since this article is about spring boot and hibernate integration, we are injecting hibernate sessionfactory and getting session out of it. In next post we will be discussing about spring data with spring boot.

UserDaoImpl.java
@Component public class UserDaoImpl implements UserDao { @PersistenceContext private EntityManager entityManager; public List getUserDetails() { Criteria criteria = entityManager.unwrap(Session.class).createCriteria(UserDetails.class); return criteria.list(); } }

SQL

Following are some sample DML. We will be creating some dummy user details using following insert statements.

create table User_Details (id integer not null auto_increment, email varchar(255), first_Name varchar(255), last_Name varchar(255), password varchar(255), primary key (id)) ENGINE=InnoDB; INSERT INTO user_details(email,first_Name,last_Name,password) VALUES ('admin@admin.com','admin','admin','admin'); INSERT INTO user_details(email,first_Name,last_Name,password) VALUES ('john@gmail.com','john','doe','johndoe'); INSERT INTO user_details(email,first_Name,last_Name,password) VALUES ('sham@yahoo.com','sham','tis','shamtis');

Run Application

1. Run Application.java as a java application. 2. Hit the url - http://localhost:8080/list. Following screen will appear. spring-boot-hibernate-result

Conclusion

I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Download the source

References

Accessing data JPA

Sspring Boot features

Suggest more topics in suggestion section or write your own article and share with your colleagues.

Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.

Further Reading: