如何修复“sessionFactory”或“hibernateTemplate”是必需的问题

2024-05-19

我正在使用 Spring Boot JPA、WEB 和 MYSQL 创建我的 Web 应用程序。它总是说“sessionFactory or hibernateTemplate是必需的”。我该如何修复它?

我已经尝试过的东西:

  1. 删除了本地 Maven 存储库中休眠核心所在的路径

  2. Put spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext在应用程序属性中

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

}

数据源.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

例外情况是由于HibernateTemplate inside HibernateDaoSupport为空。你必须打电话HibernateDaoSupport#setSessionFactory(sessionFactory)初始化HibernateTemplate.

使用构造函数注入sessionFactory,然后调用这个setter进行初始化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);
     }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何修复“sessionFactory”或“hibernateTemplate”是必需的问题 的相关文章

随机推荐

  • 使用用户定义函数 MySql 时出错

    您好 请帮我解决这个问题 提前致谢 我在数据库中定义了这些函数 CREATE FUNCTION levenshtein s1 VARCHAR 255 s2 VARCHAR 255 RETURNS INT DETERMINISTIC BEGI
  • 将数组作为参数传递

    如果我们修改作为方法内参数传递的数组的内容 则修改是在参数的副本而不是原始参数上完成的 因此结果不可见 当我们调用具有引用类型参数的方法时 会发生什么过程 这是我想问的代码示例 using System namespace Value Re
  • 将2-3-4树转换为红黑树

    我正在尝试将 2 3 4 树转换为 java 中的红黑树 但我无法弄清楚它 我将这两个基本类编写如下 以使问题简单明了 但不知道从这里到哪里去 public class TwoThreeFour
  • 下载中带有文件名的 NodeJS sendFile

    我尝试使用以下代码将文件发送给客户端 router get get myfile function req res next res sendFile other file name dat 它工作正常 但当用户从以下网址下载此文件时我需要
  • 无法连接到 MAMP 上的 phpMyAdmin

    我收到此错误消息 MySQL 说道 无法连接 设置无效 phpMyAdmin 尝试连接 MySQL 服务器 但服务器拒绝连接 您应该检查配置中的主机 用户名和密码 并确保它们与 MySQL 服务器管理员提供的信息相对应 用户和通行证是默认的
  • VSCode TypeScript 问题Matcher `$tsc-watch` 未观看

    我试图避免使用watch true in a tsconfig json配置 通过 VSCode 的任务 我正在使用基本问题匹配器 tsc watch但它没有启动tsc构建时处于监视模式 我正在添加gulp支持 我看到有gulp watch
  • 实体框架中的“it”是什么

    如果以前有人问过这个问题 请原谅我 但我的任何搜索中都没有出现 它 我有两个数据库表 Person 和 Employee 对每个类型的表进行建模 例如 Employee is a Person 在我的 edmx 设计器中 我定义了一个实体
  • 为 TFliteconverter 创建代表性数据集的正确方法是什么?

    我正在尝试推断tinyYOLO V2 with INT8权重和激活 我可以使用 TFliteConverter 将权重转换为 INT8 为了INT8激活 我必须提供代表性数据集来估计缩放因子 我创建此类数据集的方法似乎是错误的 正确的程序是
  • 弹出窗口的动态高度取决于内容,可能吗?

    是否有可能获得一个宽度始终为 400px 的弹出窗口 但根据弹出窗口中的内容动态高度 我已经看到了这个 但不知道如何将其应用到弹出窗口 调整 iframe 的宽度高度以适应其中的内容 https stackoverflow com ques
  • 在 Windows Phone silverlight 8.1 上接收 WNS 推送通知

    我有 Windows Phone 8 1 silverlight 应用程序 我想使用新框架 WNS 接收通知 我在 package appxmanifest 中有
  • (wxMaxima:表达式幂的文本

    我用过texput设置tex1的输出log x to be ln x with texput log lambda e a args e printf false ln a tex1 a 我想知道是否也可以设置类似的输出 log x n 我
  • 有没有办法限制只允许来自其他 App Engine 服务的传入请求?

    我有四个服务在 App Engine 上的同一个应用程序中运行 我有一个前端 SvelteKit 应用程序和三个后端服务 如果可能的话 我想以这样的方式设置安全性 即后端服务只接受来自前端应用程序的 HTTP 请求 前端应用程序通过其节点服
  • 如何在超级测试中模拟中间件?

    我想测试中间件是否在app js叫做 虽然我嘲笑该模块work js 它仍然运行原始代码 app js const work require work const express require require const app expr
  • 调用 MobileFirst Adapter 授权失败

    不确定以前是否曾提出过同样的问题 我尝试发表评论但无法这样做 请参阅下面的链接 不管怎样 我刚刚将开发环境升级到 MobileFirst Studio 7 1 但我们在 7 0 中创建的适配器存在问题 适配器部署没有错误 但是当我尝试从浏览
  • 如何创建用于霍夫曼编码和解码的树?

    对于我的作业 我将对霍夫曼树进行编码和解码 我在创建树时遇到问题 并且陷入困境 不要介意打印语句 它们只是让我测试并查看函数运行时的输出是什么 对于第一个 for 循环 我从主块中用于测试的文本文件中获取了所有值和索引 在第二个 for 循
  • 休眠以持久保存日期

    有没有办法告诉 Hibernate java util Date 应该持久保存 我需要这个来解决 MySQL 中缺少的毫秒分辨率问题 您能想到这种方法有什么缺点吗 您可以自己创建字段long 或者使用自定义的UserType 实施后User
  • 使用 AJAX 和 JQuery 按设定的时间间隔刷新 Rails 部分

    I have a page in my rails application that looks like 现在 我有另一个用 python 编码的人工智能应用程序 它处理视频 显示在 Rails 应用程序页面的左侧 并使用捕获的车辆及其相
  • `git push` -- 没有输出,什么也没有发生

    touch test git add test git commit m test git push u origin master 这奏效了 该文件已上传到存储库 rm test cp R website website git rm t
  • if/else 简写来定义变量

    我很难理解 if else 的 php 简写是如何描述的here https stackoverflow com questions 20233207 php if shorthand and echo in one line possib
  • 如何修复“sessionFactory”或“hibernateTemplate”是必需的问题

    我正在使用 Spring Boot JPA WEB 和 MYSQL 创建我的 Web 应用程序 它总是说 sessionFactory or hibernateTemplate是必需的 我该如何修复它 我已经尝试过的东西 删除了本地 Mav