it-swarm.com.ru

Как исправить 'sessionFactory' или 'hibernateTemplate' требуется проблема

Я создаю свое веб-приложение, используя пружинную загрузку JPA, WEB и MYSQL. Всегда говорится, что «sessionFactory или hibernateTemplate требуется». Как я могу это исправить?

Что-то я уже пробовал:

  1. Удаленный путь, где находится спящий ядро ​​в локальном репозитории Maven

  2. Поместите spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext в application.properties

  3. Поместите @Autowired private SessionFactory sessionFactory; в HibernateDaoSupport extends

  4. Созданы файлы EntityManageConfig и SessionConfig

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
4
J. Mar

Исключение связано с тем, что HibernateTemplate внутри HibernateDaoSupport имеет значение null. Вы должны вызвать HibernateDaoSupport#setSessionFactory(sessionFactory), чтобы инициализировать эту HibernateTemplate.

Используйте конструктор, чтобы внедрить sessionFactory, а затем вызвать этот установщик для инициализации 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);
     }
}
0
Ken Chan