解决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>

 



posted @ 2020-05-18 13:25  为乐而来  阅读(4042)  评论(0编辑  收藏  举报