简体   繁体   中英

Hibernate SessionFactory annotation based configuration

My recent goal is to build a spring boot application, but without any XML config files (or as less as possible) so I would like to avoid using some XML files (ie web.xml) especially for some bean definition parts.

And here comes tougher part.

I want to inject using @Autowired annotation a SessionFactory bean into classes, but everytime I try to start application I get:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'temperatureController': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: EntityManagerFactory must not be null

Ok, I understand that Spring has no SessionFactory bean because it has no EntityManagerFactory.

So I would appreciate any suggestions how to solve this, but only with configuration by annotations.

So far I read similar post to mine about specifying in @Configuration class a bean this way:

@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
    return new HibernateJpaSessionFactoryBean();
}

And then adding this line into properties file:

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

And finally @Autowired with SessionFactory should work good. But, of course for me it's not working.

Any ideas what should I do different/better?

My properties file is very basic:

spring.jpa.show-sql = true spring.datasource.password=mysql spring.datasource.username=mysql spring.datasource.testWhileIdle = true spring.jpa.hibernate.ddl-auto = update spring.datasource.validationQuery = SELECT 1 spring.datasource.url= jdbc:mysql://localhost:3306/sys spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

Usually when I want to define something simple I make a class that is similar to the following:

@Configuration
@EnableTransactionManagement
public class PersistanceJpaConfig {

    @Bean 
    public LocalSessionFactoryBean hibernateSessionFactory(DataSource dataSource) {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setPackagesToScan(new String[] { 
                  "my.entities.package" 
        });
        sessionFactory.setHibernateProperties(additionalProperties());

        return sessionFactory;
    }

    @Bean HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory);

        return transactionManager;
    }

   @Bean 
   public DataSource dataSource(){
      DriverManagerDataSource dataSource = new DriverManagerDataSource();
      dataSource.setDriverClassName("com.mysql.jdbc.Driver");
      dataSource.setUrl("jdbc:mysql://localhost:3306");
      dataSource.setUsername("user");
      dataSource.setPassword("password");
      return dataSource;
   }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "update");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL57InnoDBDialect");
        return properties;
    }

}

By using @EnableTransactionManagement and creating a bean of type LocalSessionFactoryBean , spring will automatically create a SessionFactory bean for you that you can inject/autowire anywhere.

Of course you can inject some of the configuration from properties files if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM