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

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM