【微服务】springboot 适配多数据源设计与实现
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
// 数据源配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
@Bean
@Primary
public DataSource dataSource1() {
// 配置第一个数据源
return new DataSource(); // 示例,应该是数据源的实例
}
@Bean
public DataSource dataSource2() {
// 配置第二个数据源
return new DataSource(); // 示例,应该是数据源的实例
}
}
// 实体管理器配置类
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
@Configuration
public class EntityManagerConfig {
@Primary
@Bean(name = "entityManagerFactory1")
public LocalContainerEntityManagerFactoryBean entityManagerFactory1(
EntityManager entityManager,
@Qualifier("dataSource1") DataSource dataSource1,
Map<String, Object> properties
) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource1);
em.setPackagesToScan("com.example.domain1"); // 设置实体类所在的包
em.setJpaVendorAdapter(jpaVendorAdapter());
em.setJpaPropertyMap(properties);
return em;
}
@Bean(name = "entityManagerFactory2")
public LocalContainerEntityManagerFactoryBean entityManagerFactor
评论已关闭