Skip to content

Spring boot hibernate

  • by

1. Overview

In this article, we will learn to use Hibernate with the Spring boot project.

JPA (Java Persistence API) is a specification that defines a set of concepts or guidelines for object-relational mappings and for managing persistent objects.

ORM is the mechanism of converting Java objects to database tables and also mapping Java data types to SQL data types. This allows us to interact with a relational database with no SQL.

Being a specification, JPA can’t perform any operation by itself and requires implementation. Hibernate is a standard implementation of the JPA specification.

A Hibernate is an open-source, lightweight, ORM (Object Relational Mapping) framework that simplifies the development of Java applications to interact with the database.

2. Spring boot Hibernate Dependencies

Let’s add the below dependencies to your project to get started with Hibernate

<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>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<scope>runtime</scope>
</dependency>

The spring-boot-starter-data-jpa starter dependency includes JPA APIs, JDBC, and other required libraries. This also brings in Hibernate as it is the default JPA implementation.

For this article, we will use the H2 lightweight database that can also run as an in-memory database, meaning data will not persist on the disk.

It also provides an embedded console for browsing the contents of a database and running SQL queries. By default, Spring does not enable the H2 console. To enable it, you had to add the following property in your application.properties:

spring.h2.console.enabled=true

spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=- 1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver

Additionally, you can configure the DB URL and driverClassName. After you enable and run, you would see the following statement in your console.

H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'

You would see the below h2 console when you access the http://localhost:8080/h2-console in your browser. Your JDBC URL in the below login should match the one mentioned in the log (jdbc:h2:mem:testdb).

H2 console JPA Hibernate
H2 console
H2 console with database
H2 console with database

Now, we are all set.

3. Spring boot hibernate JPA Entity

In this article, we will create a STUDENT table using JPA. To do so, create a JPA entity (object model) class with necessary attributes and run the project. Hibernate would convert the below Student class to a table in the database, referred to as Object-Relational mapping.

@Entity
public class Student {
    @Id
    @GeneratedValue
    private Long id;
    private String studentName;
	public Long getId() {
		return id;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", studentName=" + studentName + "]";
	}
}

After you run the project with the above code, the h2 console will reflect the STUDENT table in its in-memory database. The STUDENT table would have columns ID, STUDENT_NAME that are generated by using the Student class variables.

h2 console reflecting STUDENT table
h2 console reflecting STUDENT table

4. Inserting data to the table

You can create an import.sql or data.sql file in your resources folder and keep your insert queries there.

insert into STUDENT values(123, 'Siv');
insert into STUDENT values(124, 'Praj');
import sql file resources
import.sql file
h2 table
Entries in STUDENT table

5. Creating Repository

Now, let’s interact with our database using the Repository class. A Repository is the Data access layer that allows you to access our real database and provides CRUD (Create, Read, Update and Delete) methods.

In the below code, we have annotated the StudentRepository interface class with @Repository that extends JpaRepository. The JpaRepository contains all the APIs of CrudRepository and PagingAndSortingRepository . Thus, it supports CRUD operations and also pagination and sorting.

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.tedblob.springboot.hibernate.entity.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long>{

}

Now, you can access the database using the APIs of StudentRepository class. In the below SpringBootApplication class, Spring would inject the StudentRepository as a dependency that can be used for database access.

@SpringBootApplication
public class HibernateApplication implements CommandLineRunner {

	@Autowired
	StudentRepository studentRepository;
	public static void main(String[] args) {
		SpringApplication.run(HibernateApplication.class, args);
	}
	@Override
	public void run(String... args) throws Exception {
		System.out.println(studentRepository.findAll());
		
	}
}

6. Conclusion

To sum up, we have learned the basics of JPA, Hibernate, and an example to elaborate the concepts.

Leave a Reply

Your email address will not be published. Required fields are marked *