• 解决hibernate项目添加集成jpa使用EntityManager时报错No qualifying bean of type 'javax.persistence.EntityManagerFactory' available: expected single matching bean but found 2: sessionFactory,entityManagerFactory


    项目本来使用的是SrpingMVC+Hibernate,想要加入Jpa到项目中,常用的功能没问题 

    但是在Service中要使用EntityManager如下

    @PersistenceContext
    public EntityManager em;// 类似hibernate session
    
    //给子类用的
    public EntityManager getEntityManager() {
        return em;
    }


    这时候使用
    Query query = getEntityManager().createNativeQuery(sql.toString());

    报错:

    org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'Test1': Unsatisfied dependency expressed through field 'testService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testService': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available: expected single matching bean but found 2: sessionFactory,entityManagerFactory

    这是因为有二个SessionFacty,Hibernate和jap都有Iji的SessionFacey,Spring在注入实例化不知道用哪个就报错了
    解决办法:注解PersistenceContext添加unitName = "jpaEntityManagerFactory"

    @PersistenceContext(unitName = "jpaEntityManagerFactory")
        public EntityManager em;// 类似hibernate session
    
        //给子类用的
        public EntityManager getEntityManager() {
            return em;
        }
    再修改xml文件中引用entityManagerFactory也指定name="jpaEntityManagerFactory",如下代码,这样就解决了


    <!-- JPA实体管理器工厂 -->
        <bean id="entityManagerFactory" name="jpaEntityManagerFactory"
              class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
    
            <property name="jpaProperties">
                <props>
                    <prop key="hibernate.current_session_context_class">thread</prop>
                    <prop key="hibernate.hbm2ddl.auto">none</prop><!-- validate/update/create -->
                    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                    <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
    
                    <!-- 建表的命名规则 -->
                    <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
    
                </props>
            </property>
        </bean>


  • 相关阅读:
    正则表达式的先行断言(lookahead)和后行断言(lookbehind)
    正则表达式里的捕获组
    JavaScript高级程序设计8.pdf
    JavaScript高级程序设计7.pdf
    JavaScript高级程序设计6.pdf
    JavaScript高级程序设计5.pdf
    JavaScript高级程序设计4.pdf
    产品思维|腾讯工作心得:原型该画到什么程度?
    提名推荐!15个2019年最佳CSS框架
    腾讯工作心得:原型该画到什么程度?
  • 原文地址:https://www.cnblogs.com/q149072205/p/12910015.html
Copyright © 2020-2023  润新知