Menu

Hibernate with Spring Boot

Hibernate with Spring Boot

What Spring Boot Provides

Adding spring-boot-starter-data-jpa brings in Hibernate, Spring Data JPA, and transaction support. Spring Boot manages the Hibernate version. Spring Boot 3 uses Hibernate 6, and Spring Boot 4 uses Hibernate 7, so the project doesn't declare a Hibernate version.

Boot creates the EntityManagerFactory and the connection pool from the properties file. The hibernate.cfg.xml file is not needed.

spring.datasource.url=jdbc:postgresql://localhost:5432/appdb
spring.datasource.username=app
spring.datasource.password=secret
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true
public interface StudentRepository extends JpaRepository<Student, Long> {
    List<Student> findByStatus(Status status);
}

@Service
public class StudentService {
    private final StudentRepository repository;

    public StudentService(StudentRepository repository) {
        this.repository = repository;
    }

    @Transactional
    public Student create(Student student) {
        return repository.save(student);
    }
}

Code Explanation:

  • The datasource properties configure the connection, and Boot uses HikariCP by default.
  • spring.jpa.hibernate.ddl-auto maps to hibernate.hbm2ddl.auto.
  • JpaRepository provides CRUD methods, and findByStatus becomes a query based on its name.
  • @Transactional opens a transaction around the method and commits or rolls back automatically.
  • repository.save() belongs to Spring Data. It is not the removed Hibernate Session.save().

If the native Hibernate API is needed, inject an EntityManager and call unwrap(Session.class).


Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details