Spring Boot Hibernate Example

By | | Updated : 2021-10-11 | Viewed : 564 times

Spring Boot Hibernate Example

Sometimes it is required to integrate the hibernate with Spring boot. We will learn how to integrate the hibernate with Spring Boot.

Hibernate Configuration

Here we will get started with the configuration of Hibernate for Spring boot. Please have a look at the below-given code snippet.

public class MySQLConfig {
    private String DRIVER;

    private String PASSWORD;

    private String URL;

    private String USERNAME;

    private String DIALECT;

    private String SHOW_SQL;

    private String HBM2DDL_AUTO;

    private String PACKAGES_TO_SCAN;

    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        return dataSource;

    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", DIALECT);
        hibernateProperties.put("hibernate.show_sql", SHOW_SQL);
        hibernateProperties.put("hibernate.hbm2ddl.auto", HBM2DDL_AUTO);

        return sessionFactory;

    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        return transactionManager;

Notice here we configured the DataSource, LocalSessionFactoryBean, and HibernateTransactionManager. So here the properties of the DataSource are extracted from the application. properties file.

Notice here we used the @Configuration and @EnableTransactionManagement for configuring the hibernate with Spring Boot.

Spring boot Hibernate Example

We will apply now different operations on Courses using Spring Boot and Hibernate into MySQL. So please notice below the given code snippet.

public class CourseController {

    private CourseServiceImpl courseServiceImpl;

    public ResponseEntity<?> saveCourse(@RequestBody Course course) {
        try {
            return courseServiceImpl.saveCourse(course);
        } catch (Exception ex) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);

    public ResponseEntity<?> deleteCourse(@RequestBody Course course) {
        try {
            return courseServiceImpl.deleteCourse(course);
        } catch (Exception ex) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);

    @GetMapping ("/all")
    public ResponseEntity<?> getAllCourses() {
        try {
            return courseServiceImpl.getAllCourses();
        } catch (Exception ex) {

            return new ResponseEntity(HttpStatus.NOT_FOUND);

Here we are applying save, delete and fetch the courses from the MySQL. For the entire code repo please have a look at this repo SpringBoot-Hibernate-Example-App

Leave A Reply