How to fix 'sessionFactory' or 'hibernateTemplate' is required problem

Viewed 2679

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?

Something I've tried already:

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

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

  3. Put @Autowired private SessionFactory sessionFactory; in HibernateDaoSupport extends

  4. Created EntityManageConfig and SessionConfig files

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>

The error:

>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
1 Answers

The exception is due to the HibernateTemplate inside HibernateDaoSupport is being null. You have to call HibernateDaoSupport#setSessionFactory(sessionFactory) to initialise that 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);
     }
 }

And your actual DAO class:

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

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