【发布时间】:2018-10-02 21:34:55
【问题描述】:
我一直在使用spring mvc 4的项目中工作,并且JPA配置bean是在没有persistence.xml的java类中创建的,就像下面的代码一样。
package test.conf;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
public class JPAConfiguration {
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
factoryBean.setJpaVendorAdapter(vendorAdapter);
factoryBean.setDataSource(dataSource());
Properties props = new Properties();
props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
props.setProperty("hibernate.show_sql", "false");
props.setProperty("hibernate.hbm2ddl.auto", "update");
factoryBean.setJpaProperties(props);
String [] packages = {"test.model"};
factoryBean.setPackagesToScan(packages);
return factoryBean;
}
@Bean
@Primary
public DriverManagerDataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUsername("root");
dataSource.setPassword("root");
dataSource.setUrl("jdbc:mysql://localhost:3306/database");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
return dataSource;
}
@Bean
@Primary
public JpaTransactionManager transactionManager(EntityManagerFactory emf){
return new JpaTransactionManager(emf);
}
}
这工作正常,但现在,我们必须连接到第二个数据库 (ORACLE),并且需要第二个实体管理器工厂。我怎样才能做到这一点 ?我找到了在persistence.xml 上创建第二个持久性单元的示例,但该项目中没有persistence.xml。其他人教如何使用 Spring Boot 创建与多个数据源的连接,但这不是 Spring Boot 项目。
我尝试为另一个数据库创建第二个 JPAConfiguration 类,然后为每个 entitymanagerfactorybean 指定一个 factoryBean.setPersistenceUnitName("");,但似乎 Spring 搞砸了,因为它总是初始化一个持久化单元两次。
【问题讨论】:
标签: java spring entitymanager persistence.xml