Spring Boot with Hibernate

Updated on July 26th, 2019

In this article of Spring Boot, we will discuss as how to integrate Spring Boot with Hibernate. We will build a simple Spring Boot application and use Hibernate to store the data.

 

1. Application Setup

To bootstrap our application, we have the following options

  1. Spring Initializr
  2. Use IDE
  3. Use Spring Boot CLI tool.

We are using the Spring Initializr for this article. As part of the setup, we will add, Web, JPA, MySQL dependencies our application. This is how our pom.xml will look like

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

We are using MySQL for this post, in case you like to use other DB, please add the correct dependencies in your pom.xml file. With these dependencies, Spring Boot  ensure to include all the jars in the classpath including the Hibernate.

 

2. Create Entity Class

To use the hibernate to work with our data, let’s create a simple customer entity to store and retrieve customer information from the database.

@Entity
public class Customer {

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;
 private String firstName;
 private String lastName;
 private String email;

 public Customer() {
 }
 //get & set methods
}

Let’s cover some important points from our entity class:

  1. The @Entity annotation show that this class is an entity class.
  2. We are not using @Table annotation, Hibernate will map it to the table named as “Customer“.
  3. The @Id annotation mark the id field as unique id field. We are using the identity generation strategy for our example.
  4. The firstName and lastName are unmapped and it will map them to same column name as in the properties. We have the option to use @Column annotation to customize column names.

 

3. Create The Repository

Spring JPA provide a transparent integration with the underlying JPA layer using the JPA repositories. It will take care of creating repository implementations automatically, at run-time, from a repository interface. Let’s create a simple CustomerRepository for our Customer entity and let Spring JPA handle the implementation part for us:

import com.javadevjournal.data.Customer;
import org.springframework.data.repository.CrudRepository;
@Repository
public interface CustomerRepository extends JpaRepository<Customer,Long> { }

Spring JPA handle most of the work for us and we only need to define the interface. JpaRepository provide several methods to save, delete, find the entity.

 

4. Create The Service

Let’s create a simple service which will interact with the JPA repository to perform database operations:

@Service
public class CustomerService {

    @Autowired
    private CustomerRepository customerRepository;

    public List getCustomers(){
        return customerRepository.findAll();
    }
}

 

5. Test The Application

As part of the last step, let’s create the main class for our Spring Boot application:

@SpringBootApplication
public class SpringBootHibernateApplication {

 private static final Logger log = LoggerFactory.getLogger(SpringBootHibernateApplication.class);

 public static void main(String[] args) {
  SpringApplication.run(SpringBootHibernateApplication.class, args);
 }

 @Bean
 public CommandLineRunner demo(CustomerRepository repository) {
  return (args) -> {

   repository.save(new Customer("Umesh", "Awasthi", "[email protected]"));
   repository.save(new Customer("David", "Dobrik", "[email protected]"));
   repository.save(new Customer("Robert", "Hickle", "[email protected]"));
   repository.save(new Customer("Edgar", "Smith", "[email protected]"));

   // fetch all customers

   for (Customer customer: repository.findAll()) {
    log.info(customer.toString());
   }
  };
 }
}

When you run your application, you may see similar output in the console:

2019-05-21 21:30:33.470 DEBUG 72721 --- [           main] org.hibernate.SQL                   : insert into customer (email, first_name, last_name) values (?, ?, ?)
2019-05-21 21:30:33.529 DEBUG 72721 --- [           main] org.hibernate.SQL                        : insert into customer (email, first_name, last_name) values (?, ?, ?)
2019-05-21 21:30:33.533 DEBUG 72721 --- [           main] org.hibernate.SQL                        : insert into customer (email, first_name, last_name) values (?, ?, ?)
2019-05-21 21:30:33.537 DEBUG 72721 --- [           main] org.hibernate.SQL                        : insert into customer (email, first_name, last_name) values (?, ?, ?)
2019-05-21 21:30:33.667  INFO 72721 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2019-05-21 21:30:33.796 DEBUG 72721 --- [           main] org.hibernate.SQL                        : select customer0_.id as id1_0_, customer0_.email as email2_0_, customer0_.first_name as first_na3_0_, customer0_.last_name as last_nam4_0_ from customer customer0_
2019-05-21 21:30:33.807  INFO 72721 --- [           main] c.j.SpringBootHibernateApplication       : Customer{firstName='Umesh', lastName='Awasthi'}
2019-05-21 21:30:33.807  INFO 72721 --- [           main] c.j.SpringBootHibernateApplication       : Customer{firstName='David', lastName='Dobrik'}
2019-05-21 21:30:33.807  INFO 72721 --- [           main] c.j.SpringBootHibernateApplication       : Customer{firstName='Robert', lastName='Hickle'}
2019-05-21 21:30:33.807  INFO 72721 --- [           main] c.j.SpringBootHibernateApplication       : Customer{firstName='Edgar', lastName='Smith'}

 

6. Configuration File

This is how our application.properties file look like:

spring.jpa.generate-ddl=true
spring.datasource.url=jdbc:mysql://localhost:3306/spring-boot-hibernate?useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

 

7. Database Initialization

Spring Boot JPA provides the option for DDL generation. Spring JPA provides following two properties for the DDL generation

  1. spring.jpa.generate-ddl (boolean) as vendor independent.
  2. spring.jpa.hibernate.ddl-auto Hibernate specific feature.

For more information on Hibernate property, please read Initialize a Database Using Hibernate

 

Summary

In this article, we learned how to integrate Spring Boot with Hibernate. We saw how Spring Boot transparently handle the JPA integration including Hibernate. The source code for this article is available on the GitHub.

Java Development Journal

Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.

follow me on:

Leave a Reply

avatar

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

  Subscribe  
Notify of