没有[javax.persistence.EntityManager]类型的合格bean

没有[javax.persistence.EntityManager]类型的合格bean,java,spring,hibernate,jpa,Java,Spring,Hibernate,Jpa,我正在尝试构建一个全新的SpringFramework4.0项目,没有所有神奇的gradle元素,只是简单地将其踢出老派 我在这里遵循教程:并且取得了一些成功。我只是被困在这一点上 /** * */ package com.corrisoft.air.db.integration; import javax.persistence.EntityManager; import org.junit.Test; import org.junit.runner.RunWith; import

我正在尝试构建一个全新的SpringFramework4.0项目,没有所有神奇的gradle元素,只是简单地将其踢出老派

我在这里遵循教程:并且取得了一些成功。我只是被困在这一点上

/**
 * 
 */
package com.corrisoft.air.db.integration;

import javax.persistence.EntityManager;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import com.corrisoft.air.db.JPAConfiguration;

import static com.corrisoft.air.db.fixture.JPAAssertions.assertTableExists;
import static com.corrisoft.air.db.fixture.JPAAssertions.assertTableHasColumn;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { JPAConfiguration.class })
@Transactional
@TransactionConfiguration(defaultRollback = true)
public class PersonMappingIntegrationTests {

    @Autowired
    EntityManager manager;

    @Test
    public void thatItemCustomMappingWorks() throws Exception {
        assertTableExists(manager, "PERSONS");

        assertTableHasColumn(manager, "PERSONS", "FIRST_NAME");
        assertTableHasColumn(manager, "PERSONS", "LAST_NAME");
    }
}
当我运行此单元测试时,我得到以下堆栈跟踪:

SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@68c884e] to prepare test instance [com.corrisoft.air.db.integration.PersonMappingIntegrationTests@7448bc3d]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.corrisoft.air.db.integration.PersonMappingIntegrationTests': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: javax.persistence.EntityManager com.corrisoft.air.db.integration.PersonMappingIntegrationTests.manager; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManager] is defined: expected single matching bean but found 2: entityManager,org.springframework.orm.jpa.SharedEntityManagerCreator#0
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:384)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:326)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:212)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: javax.persistence.EntityManager com.corrisoft.air.db.integration.PersonMappingIntegrationTests.manager; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManager] is defined: expected single matching bean but found 2: entityManager,org.springframework.orm.jpa.SharedEntityManagerCreator#0
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 26 more
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManager] is defined: expected single matching bean but found 2: entityManager,org.springframework.orm.jpa.SharedEntityManagerCreator#0
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:967)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 28 more
根据观察和研究,它似乎告诉我有两个EntityManager类。第一个来自hibernate JPA jar,但找不到第二个。它似乎在告诉我它在Spring ORM中,但在该类中没有定义

以下是测试中使用的JPA配置类:

/**
 * 
 */
package com.corrisoft.air.db;

import java.sql.SQLException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.corrisoft.air.db.repository.PersonsRepository;

/**
 * @author Corrisoft Android Development
 * 
 */
@Configuration
@EnableJpaRepositories(basePackages = "com.corrisoft.db.repository", includeFilters = @ComponentScan.Filter(value = { PersonsRepository.class }, type = FilterType.ASSIGNABLE_TYPE))
@EnableTransactionManagement
public class JPAConfiguration {

    @Bean
    public DataSource dataSource() throws SQLException {
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        return builder.setType(EmbeddedDatabaseType.H2).build();
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() throws SQLException {

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("com.corrisoft.air.model");
        factory.setDataSource(dataSource());
        factory.afterPropertiesSet();

        return factory.getObject();
    }

    @Bean
    public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
        return entityManagerFactory.createEntityManager();
    }

    @Bean
    public PlatformTransactionManager transactionManager() throws SQLException {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }

    @Bean
    public HibernateExceptionTranslator hibernateExceptionTranslator() {
        return new HibernateExceptionTranslator();
    }
}

EntityManager
接口属于JPA,由JPA提供者(如Eclipse)而不是Spring实现,并且它有自己的注入注释:
@PersistenceContext
EntityManager
对象是事务范围的对象,不应像您所做的那样作为bean公开。相反,可以使用JPA注释插入
EntityManager

@PersistenceContext
EntityManager em;
或者,因为看起来您正在尝试使用Spring存储库,所以请插入存储库:

@Autowired
PersonRepository pr;

尽管这篇文章已经很老了,并且已经有了bean的回答,但我在SpringIO网站上的官方TurrialSpring数据jpa中遇到了同样的问题

当前的spring数据jpa示例/spring io指南检测到至少2个实现接口“EntityManager”的bean。您必须帮助spring连接到什么实现。我建议添加一个限定符

在类JPA配置中添加:

@Bean
@Qualifier(value = "entityManager")
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
    return entityManagerFactory.createEntityManager();
}
在测试类中添加:

@Autowired
@Qualifier(value = "entityManager")
EntityManager manager;
希望对你有帮助

我不一定要使用“PersistenceContext”,因为spring处理事务管理器、entitymanager、bean、datasource等的创建。。
“PerssenceContext”注释基本上是为应用服务器/ejb兼容容器的容器管理entityfactory定义的

否,错误消息告诉您已经定义了多个bean,这些bean实现了
EntityManager
,我们需要查看您的配置以确定位置。@chrylis Hmmm…我在我的项目中搜索了EntityManager,只找到了一些在JPA配置中返回的位置,该配置几乎完全复制自教程。你还需要看其他配置吗?@chrylis我有点迷路了,因为我正在关注faith的教程,希望它在完成后会有意义。发布
jpa配置
class。如果您找到了返回
EntityManager
的位置,这可能就是问题所在。@chrylis Done。谢谢你的帮助。所以,这是教程中的一个bug。感谢您的帮助。为meI工作的自动连接respository的第二个选项在
@Transactional
范围和此解决方案方面遇到了问题,使用
@PersistentContext
注入了正确的
EntityManager
实例(
SharedEntityManagerBean
)。
JpaTransactionManager
@Transactional
方法结束后没有关闭会话(也没有刷新会话)。只有多个事务管理器和多个数据源存在此问题。