Spring ORM - Persistence Hibernate



Hibernate Persistence Unit defines the various aspects related to data persistence like following.

  • Persistence Unit − A persistence unit containing all the details. It's name is used to get reference in spring context.

  • Database url and credentials − In properties section, we pass the database related values.

  • show_sql − to show the generated sql queries

  • hbm2ddl − to allow hibernate to create tables.

Create persistence configuration as AppConfig.

AppConfig.java

package com.tutorialspoint.jpa;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.hibernate.HibernateTransactionManager;
import org.springframework.orm.jpa.hibernate.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScans(value = { @ComponentScan("com.tutorialspoint.jpa.dao"),
@ComponentScan("com.tutorialspoint.jpa.service") })
public class AppConfig {
   @Bean
   public LocalSessionFactoryBean sessionFactory() {
      LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
      sessioFactory.setDataSource(dataSource());
      sessionFactory.setPackagesToScan("com.tutorialspoint.jpa.entity");
      sessionFactory.setHibernateProperties(hibernateProperties());
      return sessionFactory;
   }

   @Bean
   public DataSource dataSource() {
      org.springframework.jdbc.datasource.DriverManagerDataSource dataSource = new org.springframework.jdbc.datasource.DriverManagerDataSource();
      dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
      dataSource.setUrl("jdbc:mysql://localhost:3306/tutorialspoint");
      dataSource.setUsername("guest");
      dataSource.setPassword("guest123");
      return dataSource;
   }

   private Properties hibernateProperties() {
      Properties properties = new Properties();
      properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
      properties.put("hibernate.show_sql", "true");
      properties.put("hibernate.hbm2ddl.auto", "create");
      return properties;
   }

   @Bean
   public HibernateTransactionManager transactionManager() {
      HibernateTransactionManager txManager = new HibernateTransactionManager();
      txManager.setSessionFactory(sessionFactory().getObject());
      return txManager;
   }
}
Advertisements