Hibernate SessionFactory基于注解的配置 [英] Hibernate SessionFactory annotation based configuration

查看:330
本文介绍了Hibernate SessionFactory基于注解的配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近的目标是构建一个Spring Boot应用程序,但是没有任何XML配置文件(或尽可能少),因此我想避免使用某些XML文件(例如web.xml),尤其是对于某些bean定义部分.

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 (i.e. web.xml) especially for some bean definition parts.

这是更难的部分.

我想使用@Autowired注释将SessionFactory bean注入类,但是每次尝试启动应用程序时,我都会得到:

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:创建名称为'temperatureController'的bean时出错:通过字段'sessionFactory'表示的不满足的依赖关系;嵌套的异常是org.springframework.beans.factory.BeanCreationException:创建名称为'sessionFactory'的bean时出错:FactoryBean在对象创建时抛出了异常;嵌套异常为java.lang.IllegalStateException:EntityManagerFactory不能为null

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

好的,我知道Spring没有SessionFactory bean,因为它没有EntityManagerFactory.

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.

到目前为止,我读过类似的文章,内容涉及以这种方式在@Configuration类中指定bean:

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

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

最后,将@Autowired与SessionFactory一起工作应该很好. 但是,对我来说当然是行不通的.

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 =更新 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

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;
    }

}

通过使用@EnableTransactionManagement并创建类型为LocalSessionFactoryBean的bean,spring将自动为您创建一个SessionFactory bean,您可以在任何地方注入/自动装配

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.

这篇关于Hibernate SessionFactory基于注解的配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆