MySQL,postgresql 我想将相同的数据放在同一个名称表中。
错误
WARN 2017-07-04 14:53:03 o.s.c.s.GenericApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tempMasterServiceImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
INFO 2017-07-04 14:53:03 o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
INFO 2017-07-04 14:53:03 o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
ERROR 2017-07-04 14:53:03 o.s.t.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@7af44dd0] to prepare test instance [jp.co.ui2.dev.server.c_one.tempServiceTest@26d8c9da]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tempMasterServiceImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:357) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
... 25 common frames omitted
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:587) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:546) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:712) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:685) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:354) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
... 39 common frames omitted
test.properties
//mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:8888/testdb
jdbc.username=test
jdbc.password=test
//postgresql
jdbc.driverClassName2=org.postgresql.Driver
jdbc.url2=jdbc:postgresql://localhost:5432/postgres
jdbc.username2=postgres
jdbc.password2=postgres
TestConfig.java
@Configuration
@Import({ testServerConfig.class })
public class TestConfig
{
@Bean
public PropertiesFactoryBean prop() {
PropertiesFactoryBean f = new PropertiesFactoryBean();
f.setLocations(new Resource[] {
new FileSystemResource("src/main/webapp/WEB-INF/config.properties"),
new ClassPathResource("test.properties", getClass())
});
return f;
}
}
tempServiceTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class, loader =AnnotationConfigContextLoader.class)
public class ShopInfoServiceTest extends AbstractServiceTest
{
@Autowired
private tempMasterService tempService;
@Test
public void testCustomCode()
{
// insert
doInTransaction(new Runnable() {
@Override
public void run() {
tempMaster info = createTemp( );
tempService.insertTempMaster(info);
}
});
}
private tempMaster createTemp () {
tempMaster xxx = new tempMaster ();
xxx.setTempId(1);
xxx.setTempName("chaco1234");
xxx.setDescription("tttttt2232");
xxx.setUserId("admin");
return xxx;
}
}
testServerConfig.java
@Configuration
@ComponentScan(basePackages = { "com.co.test.dev" }, excludeFilters = {
@Filter(type = FilterType.ANNOTATION, value = Controller.class),
@Filter(type = FilterType.ANNOTATION, value = Configuration.class) })
@EnableTransactionManagement
@EnableScheduling
@EnableCaching
@ImportResource("classpath:job-context.xml")
public class testServerConfig
{
@Autowired
private ApplicationContext ctx;
@Autowired
private ResourceLoader resourceLoader;
@Value("#{prop['jdbc.driverClassName'] ?: ''}")
private String jdbcDriverClassName;
@Value("#{prop['jdbc.url'] ?: ''}")
private String jdbcUrl;
@Value("#{prop['jdbc.username'] ?: ''}")
private String jdbcUsername;
@Value("#{prop['jdbc.password'] ?: ''}")
private String jdbcPassword;
@Value("#{prop['jdbc.driverClassName2'] ?: ''}")
private String jdbcDriverClassName2;
@Value("#{prop['jdbc.url2'] ?: ''}")
private String jdbcUrl2;
@Value("#{prop['jdbc.username2'] ?: ''}")
private String jdbcUsername2;
@Value("#{prop['jdbc.password2'] ?: ''}")
private String jdbcPassword2;
@Value("#{prop['hibernate.dialect2'] ?: ''}")
private String hibernateDialect2;
@Value("#{prop['jdbc.initialSize'] ?: '0'}")
private int jdbcInitialSize;
@Value("#{prop['jdbc.maxActive'] ?: '50'}")
private int jdbcMaxActive;
@Value("#{prop['jdbc.maxIdle'] ?: '5'}")
private int jdbcMaxIdle;
@Value("#{prop['jdbc.maxWait'] ?: '5000'}")
private int jdbcMaxWait;
@Value("#{prop['jdbc.minIdle'] ?: '0'}")
private int jdbcMinIdle;
@Value("#{prop['jdbc.testWhileIdle'] ?: 'false'}")
private boolean jdbcTestWhileIdle;
@Value("#{prop['jdbc.testOnBorrow'] ?: 'false'}")
private boolean jdbcTestOnBorrow;
@Value("#{prop['jdbc.validationQuery'] ?: ''}")
private String jdbcValidationQuery;
@Value("#{prop['hibernate.hbm2ddl.auto'] ?: 'update'}")
private String hibernateDDLAuto;
@Value("#{prop['hibernate.dialect'] ?: ''}")
private String hibernateDialect;
@Value("#{prop['hibernate.search.indexBase'] ?: ''}")
private String searchIndexBase;
@Value("#{prop['hibernate.packages.to.scan'] ?: ''}")
private String packagesToScan;
protected String getRealPath(String path)
{
if ((ctx != null) && (ctx instanceof WebApplicationContext)
&& (((WebApplicationContext) ctx).getServletContext() != null)) return ((WebApplicationContext) ctx)
.getServletContext().getRealPath(path);
else return "src/main/webapp/" + path;
}
@Bean
public PropertiesFactoryBean prop()
{
String path = getRealPath("/WEB-INF/config.properties");
PropertiesFactoryBean f = new PropertiesFactoryBean();
f.setLocation(new FileSystemResource(path));
return f;
}
@Bean(name="dataSource")
public DataSource dataSource()
{
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(jdbcDriverClassName);
ds.setUrl(jdbcUrl);
ds.setUsername(jdbcUsername);
ds.setPassword(jdbcPassword);
ds.setInitialSize(jdbcInitialSize);
ds.setMaxActive(jdbcMaxActive);
ds.setMaxIdle(jdbcMaxIdle);
ds.setMaxWait(jdbcMaxWait);
ds.setMinIdle(jdbcMinIdle);
ds.setTestWhileIdle(jdbcTestWhileIdle);
ds.setValidationQuery(jdbcValidationQuery);
return ds;
}
@Bean(name="dataSource2")
public DataSource dataSource2()
{
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(jdbcDriverClassName2);
ds.setUrl(jdbcUrl2);
ds.setUsername(jdbcUsername2);
ds.setPassword(jdbcPassword2);
ds.setInitialSize(jdbcInitialSize);
ds.setMaxActive(jdbcMaxActive);
ds.setMaxIdle(jdbcMaxIdle);
ds.setMaxWait(jdbcMaxWait);
ds.setMinIdle(jdbcMinIdle);
ds.setTestWhileIdle(jdbcTestWhileIdle);
ds.setValidationQuery(jdbcValidationQuery);
return ds;
}
@Bean(name="entityManagerFactoryBean")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
{
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
if (packagesToScan != null) {
String[] pts = packagesToScan.split(",");
emf.setPackagesToScan(pts);
}
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties p = new Properties();
p.setProperty("hibernate.archive.autodetection", "class");
p.setProperty("hibernate.dialect", hibernateDialect);
p.setProperty("hibernate.show_sql", "false");
p.setProperty("hibernate.format_sql", "true");
p.setProperty("hibernate.hbm2ddl.auto", hibernateDDLAuto);
//naming-strategy
p.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
emf.setJpaProperties(p);
return emf;
}
@Bean(name="entityManagerFactoryBean2")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean2()
{
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
if (packagesToScan != null) {
String[] pts = packagesToScan.split(",");
emf.setPackagesToScan(pts);
}
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties p = new Properties();
p.setProperty("hibernate.archive.autodetection", "class");
p.setProperty("hibernate.dialect2", hibernateDialect2);
p.setProperty("hibernate.show_sql", "false");
p.setProperty("hibernate.format_sql", "true");
p.setProperty("hibernate.hbm2ddl.auto", hibernateDDLAuto);
//naming-strategy
p.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
emf.setJpaProperties(p);
return emf;
}
@Bean(name="transactionManager")
public PlatformTransactionManager transactionManager()
{
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return tm;
}
@Bean(name="transactionManager2")
public PlatformTransactionManager transactionManager2()
{
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactoryBean2().getObject());
return tm;
}
@Bean
public EhCacheCacheManager cacheManager()
{
EhCacheCacheManager cm = new EhCacheCacheManager();
cm.setCacheManager(ehcache().getObject());
return cm;
}
@Bean
public EhCacheManagerFactoryBean ehcache()
{
EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();
factory.setConfigLocation(resourceLoader.getResource("classpath:ehcache.xml"));
return factory;
}
@Bean(name = "configSftpSessionfactoryId")
public DefaultSftpSessionFactory sftpSessionFactory() {
DefaultSftpSessionFactory sftp = new DefaultSftpSessionFactory();
sftp.setHost(sftpHost);
sftp.setPort(sftpPort);
sftp.setUser(sftpUser);
sftp.setPassword(sftpPassword);
if (sftpPrivateKey != null && !"".equals(sftpPrivateKey)) {
sftp.setPrivateKey(resourceLoader.getResource(sftpPrivateKey));
sftp.setPrivateKeyPassphrase(sftpPrivateKeyPassphrase);
}
sftp.setAllowUnknownKeys(true);
return sftp;
}
}
tempMasterServiceImpl
@Service
@Transactional
@SwabAdminAuthCheck
public class tempMasterImpl implements tempMasterService{
private Logger logger = LoggerFactory.getLogger(getClass());
@PersistenceContext
private EntityManager em;
@Override
public void insertTempMaster(tempMaster obj) throws SwabException {
Query keyq = em.createQuery("select tempId from tempMaster where userId = :userId");
keyq.setParameter("userId", obj.getUserId());
Integer tmepId = null;
try{
tempId = (Integer)keyq.getSingleResult();
obj.setTempId( tempId );
} catch (NoResultException nre){
}
tempMaster searchData = em.find(tempMaster.class, obj);
if (searchData == null) {
logger.debug("insert");
em.persist(obj);
} else {
logger.debug("update");
em.merge(obj);
}
}
}
的persistence.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyTenSevenDialect" />
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.EmbeddedDriver" />
</properties>
</persistence-unit>
</persistence>