Spring Boot Hibernate Example

By | | Updated : 2021-05-08 | Viewed : 153 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.

MySQLConfig.java
@Configuration
@EnableTransactionManagement
public class MySQLConfig {
    @Value("${spring.datasource.driver-class-name}")
    private String DRIVER;

    @Value("${spring.datasource.password}")
    private String PASSWORD;

    @Value("${spring.datasource.url}")
    private String URL;

    @Value("${spring.datasource.username}")
    private String USERNAME;

    @Value("${spring.jpa.properties.hibernate.dialect}")
    private String DIALECT;

    @Value("${spring.jpa.properties.hibernate.show_sql}")
    private String SHOW_SQL;

    @Value("${spring.jpa.hibernate.ddl-auto}")
    private String HBM2DDL_AUTO;

    @Value("${entitymanager.packagesToScan}")
    private String PACKAGES_TO_SCAN;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(DRIVER);
        dataSource.setUrl(URL);
        dataSource.setUsername(USERNAME);
        dataSource.setPassword(PASSWORD);
        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(PACKAGES_TO_SCAN);
        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", DIALECT);
        hibernateProperties.put("hibernate.show_sql", SHOW_SQL);
        hibernateProperties.put("hibernate.hbm2ddl.auto", HBM2DDL_AUTO);
        sessionFactory.setHibernateProperties(hibernateProperties);

        return sessionFactory;
    }

    @Bean
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        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.

CourseController.java
@RestController
@RequestMapping("/course/api")
public class CourseController {

    @Autowired
    private CourseServiceImpl courseServiceImpl;

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

    @DeleteMapping("/delete")
    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