如何修复"sessionFactory"或"hibernateTemplate"是必需的问题 [英] How to fix 'sessionFactory' or 'hibernateTemplate' is required problem

查看:63
本文介绍了如何修复"sessionFactory"或"hibernateTemplate"是必需的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Boot JPA,WEB和MYSQL创建我的Web应用程序.它总是说"sessionFactoryhibernateTemplate是必需的".我该如何解决?

I'm creating my web app by using spring boot JPA, WEB and MYSQL. It always says that "sessionFactory or hibernateTemplate is required". How can I fix it?

我已经尝试过的东西:

  1. 已删除本地Maven存储库中处于休眠状态的核心的路径

  1. Deleted path where hibernate core on in local maven repo

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext放入application.properties

Put spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext in application.properties

@Autowired private SessionFactory sessionFactory;放入HibernateDaoSupport扩展

Put @Autowired private SessionFactory sessionFactory; in HibernateDaoSupport extends

创建了EntityManageConfigSessionConfig文件

EntityManageConfig.java:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManageFactoryPrimary",
        transactionManagerRef = "transactionManagerPrimary",
        basePackages = {"com.coolspen.rjb.dao"}
)
public class EntityManageConfig {

    @Autowired
    @Qualifier("myDataSource")
    private DataSource myDataSource;

    @Primary
    @Bean(name = "entityManagerPrimary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder){
        return entityManageFactory(builder).getObject().createEntityManager();
    }   

    @Primary
    @Bean(name = "entityManageFactoryPrimary")
    public LocalContainerEntityManagerFactoryBean entityManageFactory(EntityManagerFactoryBuilder builder){
        LocalContainerEntityManagerFactoryBean entityManagerFactory =  builder.dataSource(myDataSource)
                .packages("com.coolspen.rjb.model").build();
        Properties jpaProperties = new Properties();
        jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        jpaProperties.put("hibernate.physical_naming_strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
        jpaProperties.put("hibernate.connection.charSet", "utf-8");
        jpaProperties.put("hibernate.show_sql", "false");
        jpaProperties.put("hibernate.current_session_context_class", "org.springframework.orm.hibernate5.SpringSessionContext");
        entityManagerFactory.setJpaProperties(jpaProperties);
        return entityManagerFactory;
    }

    @Primary
    @Bean(name = "transactionManagerPrimary")
    public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManageFactory(builder).getObject());
    }   

}

SessionConfig.java:

@Configuration
public class SessionConfig {    
@Autowired
    @Qualifier("myDataSource")
    private DataSource myDataSource;

    @Bean
    public HibernateTransactionManager getTransationManager() {
        return new HibernateTransactionManager(getSessionFactory());
    }

    @Bean
    public SessionFactory getSessionFactory() {
        LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(myDataSource);
        builder.scanPackages("com.coolspen.rjb.dao");
        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
        builder.addProperties(hibernateProperties);
        return builder.buildSessionFactory();
    }
}

DepartmentDao.java

@SuppressWarnings(value = "all")
@Repository
public class DepartmentDao extends BaseHibernateDao<Department,java.lang.Integer>{

    public Class getEntityClass() {
        return Department.class;
    }

    public Page<Department> findPage(DepartmentQuery query) {

        StringBuilder hqlSb = new StringBuilder("SELECT t FROM  Department t WHERE 1=1 ");
        if(isNotEmpty(query.getDepartmentid())) {
            hqlSb.append(" AND  t.departmentid = :departmentid ");
        }
        if(isNotEmpty(query.getDepartmentName())) {
            hqlSb.append(" AND  t.departmentName = :departmentName ");
        }
        if(isNotEmpty(query.getRemark())) {
            hqlSb.append(" AND  t.remark = :remark ");
        }
        if(isNotEmpty(query.getCreatedateBegin())) {
            hqlSb.append(" AND  t.createdate >= :createdateBegin ");
        }
        if(isNotEmpty(query.getCreatedateEnd())) {
            hqlSb.append(" AND t.createdate <= :createdateEnd ");
        }
        if(isNotEmpty(query.getCreator())) {
            hqlSb.append(" AND  t.creator = :creator ");
        }
        if(isNotEmpty(query.getModifier())) {
            hqlSb.append(" AND  t.modifier = :modifier ");
        }
        if(isNotEmpty(query.getModifydateBegin())) {
            hqlSb.append(" AND  t.modifydate >= :modifydateBegin ");
        }
        if(isNotEmpty(query.getModifydateEnd())) {
            hqlSb.append(" AND t.modifydate <= :modifydateEnd ");
        }
        if(isNotEmpty(query.getIsAvaliable())) {
            hqlSb.append(" AND  t.isAvaliable = :isAvaliable ");
        }
        if(isNotEmpty(query.getIsDeleted())) {
            hqlSb.append(" AND  t.isDeleted = :isDeleted ");
            }
        System.out.println("finished1");
        return pageQuery(hqlSb.toString(),query);
    }


}

BaseHibernateDao.java

@SuppressWarnings(value = "all")
public abstract class BaseHibernateDao<E, PK extends Serializable>
        extends
            HibernateDaoSupport implements EntityDao<E, PK> {
    /**
     * Logger for subclass
     */
    protected Log log = LogFactory.getLog(getClass());
    public abstract Class getEntityClass();

    @Autowired
    private SessionFactory sessionFactory;
......

}

datasource.xml

 <!--Hibernate Annotation SessionFatory -->
     <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
                <value>com.**.model</value>
                <value>com.**.entity</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">com.coolspen.rjb</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.query.substitutions">true 1, false 0</prop>
                <prop key="hibernate.default_batch_fetch_size">4000</prop>
                <prop key="hibernate.jdbc.batch_size">200</prop>
            </props>
        </property>
    </bean>

错误:

>Error starting ApplicationContext. To display the conditions report re-run >your application with 'debug' enabled.
2018-12-27 19:05:58.020 ERROR 18860 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'departmentDao' defined in file [E:\eclipse_project\rjb-13\target\classes\com\coolspen\rjb\dao\DepartmentDao.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1745) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at com.coolspen.rjb.Rjb13Application.main(Rjb13Application.java:21) [classes/:na]
Caused by: java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
    at org.springframework.orm.hibernate5.support.HibernateDaoSupport.checkDaoConfig(HibernateDaoSupport.java:122) ~[spring-orm-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44) ~[spring-tx-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    ... 16 common frames omitted

推荐答案

该异常是由于HibernateDaoSupport中的HibernateTemplate为空.您必须调用HibernateDaoSupport#setSessionFactory(sessionFactory)来初始化HibernateTemplate.

The exception is due to the HibernateTemplate inside HibernateDaoSupport is being null. You have to call HibernateDaoSupport#setSessionFactory(sessionFactory) to initialise that HibernateTemplate.

使用构造函数注入sessionFactory,然后调用此setter初始化HibernateTemplate:

Use constructor to inject sessionFactory and then call this setter to initialise HibernateTemplate:

public abstract class BaseHibernateDao<E, PK extends Serializable>
    extends HibernateDaoSupport implements EntityDao<E, PK> {

     @Autowired
     public BaseHibernateDao(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
     }
 }

您的实际DAO课:

@Repository
public class DepartmentDao extends BaseHibernateDao<Department,java.lang.Integer>{

    public DepartmentDao(SessionFactory sessionFactory) {
          super(sessionFactory);
     }
}

这篇关于如何修复"sessionFactory"或"hibernateTemplate"是必需的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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