Spring Boot / Thymeleaf / Hibernate: Sessionfactory Bean with Java Annotations

前端 未结 3 1256
悲哀的现实
悲哀的现实 2020-12-19 22:45

I\'ve created a Spring Boot web application with IntelliJ using Thymeleaf and Hibernate. I\'ve come so far that I can create all the db connections and it\'s working fine. A

3条回答
  •  借酒劲吻你
    2020-12-19 23:21

    Since you are using spring boot you should use XML free configuration for your database configuration . To integrate spring boot with hibernate you will need to create LocalSessionFactoryBean , DataSource ,HibernateTransactionManager and PersistenceExceptionTranslationPostProcessor bean like this:

    @Configuration
    public class DatabaseConfig {
    
        @Bean
        public LocalSessionFactoryBean sessionFactory() {
            LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
            sessionFactory.setDataSource(dataSource());
            sessionFactory.setPackagesToScan("com.example.model");
            sessionFactory.setHibernateProperties(hibernateProperties());
    
            return sessionFactory;
        }
    
        @Bean
        public DataSource dataSource() {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("org.postgresql.Driver");
            dataSource.setUrl("jdbc:postgresql://localhost:5432/testdb");
            dataSource.setUsername("root");
            dataSource.setPassword("root");
    
            return dataSource;
        }
    
        @Bean
        @Autowired
        public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
    
            HibernateTransactionManager txManager = new HibernateTransactionManager();
            txManager.setSessionFactory(sessionFactory);
    
            return txManager;
        }
    
        @Bean
        public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
            return new PersistenceExceptionTranslationPostProcessor();
        }
    
        Properties hibernateProperties() {
            Properties properties = new Properties();
            properties.setProperty("hibernate.ddl-auto", "update");
            properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
            return properties;
        }
    }
    

    In the above database config i have used postgreSQL database .

    To get instance of sessionFactory autowire SessionFactory interface like this:

     @Autowired
     SessionFactory sessionFactory;
    

提交回复
热议问题