Spring-data-jpa支持

对于数据源的配置可以沿用上例中DataSourceConfig的实现。

新增对第一数据源的JPA配置,注意两处注释的地方,用于指定数据源对应的Entity实体和Repository定义位置,用@Primary区分主数据源。

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactoryPrimary",
transactionManagerRef="transactionManagerPrimary",
basePackages= { "com.didispace.domain.p" }) //设置Repository所在位置
public class PrimaryConfig { @Autowired @Qualifier("primaryDataSource")
private DataSource primaryDataSource; @Primary
@Bean(name = "entityManagerPrimary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
} @Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
return builder
.dataSource(primaryDataSource)
.properties(getVendorProperties(primaryDataSource))
.packages("com.didispace.domain.p") //设置实体类所在位置
.persistenceUnit("primaryPersistenceUnit")
.build();
} @Autowired
private JpaProperties jpaProperties; private Map<String, String> getVendorProperties(DataSource dataSource) {
return jpaProperties.getHibernateProperties(dataSource);
} @Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
} }

  

新增对第二数据源的JPA配置,内容与第一数据源类似,具体如下:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactorySecondary",
transactionManagerRef="transactionManagerSecondary",
basePackages= { "com.didispace.domain.s" }) //设置Repository所在位置
public class SecondaryConfig { @Autowired @Qualifier("secondaryDataSource")
private DataSource secondaryDataSource; @Bean(name = "entityManagerSecondary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactorySecondary(builder).getObject().createEntityManager();
} @Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {
return builder
.dataSource(secondaryDataSource)
.properties(getVendorProperties(secondaryDataSource))
.packages("com.didispace.domain.s") //设置实体类所在位置
.persistenceUnit("secondaryPersistenceUnit")
.build();
} @Autowired
private JpaProperties jpaProperties; private Map<String, String> getVendorProperties(DataSource dataSource) {
return jpaProperties.getHibernateProperties(dataSource);
} @Bean(name = "transactionManagerSecondary")
PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
} }

  

完成了以上配置之后,主数据源的实体和数据访问对象位于:com.didispace.domain.p,次数据源的实体和数据访问接口位于:com.didispace.domain.s

分别在这两个package下创建各自的实体和数据访问接口

  • 主数据源下,创建User实体和对应的Repository接口

    @Entity
    public class User { @Id
    @GeneratedValue
    private Long id; @Column(nullable = false)
    private String name; @Column(nullable = false)
    private Integer age; public User(){} public User(String name, Integer age) {
    this.name = name;
    this.age = age;
    } // 省略getter、setter }
    public interface UserRepository extends JpaRepository<User, Long> { }

      

  • 从数据源下,创建Message实体和对应的Repository接口
    @Entity
    public class Message { @Id
    @GeneratedValue
    private Long id; @Column(nullable = false)
    private String name; @Column(nullable = false)
    private String content; public Message(){} public Message(String name, String content) {
    this.name = name;
    this.content = content;
    } // 省略getter、setter }
    public interface MessageRepository extends JpaRepository<Message, Long> { }

      

    接下来通过测试用例来验证使用这两个针对不同数据源的配置进行数据操作。

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(Application.class)
    public class ApplicationTests { @Autowired
    private UserRepository userRepository;
    @Autowired
    private MessageRepository messageRepository; @Test
    public void test() throws Exception { userRepository.save(new User("aaa", 10));
    userRepository.save(new User("bbb", 20));
    userRepository.save(new User("ccc", 30));
    userRepository.save(new User("ddd", 40));
    userRepository.save(new User("eee", 50)); Assert.assertEquals(5, userRepository.findAll().size()); messageRepository.save(new Message("o1", "aaaaaaaaaa"));
    messageRepository.save(new Message("o2", "bbbbbbbbbb"));
    messageRepository.save(new Message("o3", "cccccccccc")); Assert.assertEquals(3, messageRepository.findAll().size()); } }

    源码来源

Spring Boot教程(三十二)多数据源配置与使用(2)的更多相关文章

  1. Spring Boot教程(十二)整合elk(1)

    elk 简介 Elasticsearch是个开源分布式搜索引擎,它的特点有:分布式,零配置,自动发现,索引自动分片,索引副本机制,restful风格接口,多数据源,自动搜索负载等. Logstash是 ...

  2. Spring Boot 2.X(十二):定时任务

    简介 定时任务是后端开发中常见的需求,主要应用场景有定期数据报表.定时消息通知.异步的后台业务逻辑处理.日志分析处理.垃圾数据清理.定时更新缓存等等. Spring Boot 集成了一整套的定时任务工 ...

  3. spring boot 常见三十四问

    Spring Boot 是微服务中最好的 Java 框架. 我们建议你能够成为一名 Spring Boot 的专家. 问题一 Spring Boot.Spring MVC 和 Spring 有什么区别 ...

  4. spring boot实战(第十二篇)整合RabbitMQ

    前言 最近几篇文章将围绕消息中间件RabbitMQ展开,对于RabbitMQ基本概念这里不阐述,主要讲解RabbitMQ的基本用法.Java客户端API介绍.spring Boot与RabbitMQ整 ...

  5. Spring Boot教程(十六)属性配置文件详解(1)

    相信很多人选择Spring Boot主要是考虑到它既能兼顾Spring的强大功能,还能实现快速开发的便捷.我们在Spring Boot使用过程中,最直观的感受就是没有了原来自己整合Spring应用时繁 ...

  6. Spring Boot2 系列教程(三十二)Spring Boot 整合 Shiro

    在 Spring Boot 中做权限管理,一般来说,主流的方案是 Spring Security ,但是,仅仅从技术角度来说,也可以使用 Shiro. 今天松哥就来和大家聊聊 Spring Boot ...

  7. 学习Spring Boot:(十二)Mybatis 中自定义枚举转换器

    前言 在 Spring Boot 中使用 Mybatis 中遇到了字段为枚举类型,数据库存储的是枚举的值,发现它不能自动装载. 解决 内置枚举转换器 MyBatis内置了两个枚举转换器分别是:org. ...

  8. Spring Boot教程(十四)快速入门

    快速入门 本章主要目标完成Spring Boot基础项目的构建,并且实现一个简单的Http请求处理,通过这个例子对Spring Boot有一个初步的了解,并体验其结构简单.开发快速的特性. 系统要求: ...

  9. Spring Boot 入门(十二):报表导出,对比poi、jxl和esayExcel的效率

    本片博客是紧接着Spring Boot 入门(十一):集成 WebSocket, 实时显示系统日志写的 关于poi.jxl和esayExcel的介绍自行百度. jxl最多支持03版excel,所以单个 ...

  10. 【Spring Boot学习之十二】mybatis3 分页打印sql日志

    环境 eclipse 4.7 jdk 1.8 Spring Boot 1.5.2 参考: mybatis手册 Mybatis的插件 PageHelper 分页查询使用方法MyBatis中Like语句使 ...

随机推荐

  1. 树状数组+二维前缀和(A.The beautiful values of the palace)--The Preliminary Contest for ICPC Asia Nanjing 2019

    题意: 给你螺旋型的矩阵,告诉你那几个点有值,问你某一个矩阵区间的和是多少. 思路: 以后记住:二维前缀和sort+树状数组就行了!!!. #define IOS ios_base::sync_wit ...

  2. WPF贝塞尔曲线示例

    WPF贝塞尔曲线示例 贝塞尔曲线在之前使用SVG的时候其实就已经有接触到了,但应用未深,了解的不是很多,最近在进行图形操作的时候需要用到贝塞尔曲线,所以又重新来了解WPF中贝塞尔曲线的绘制. 一阶贝塞 ...

  3. JAVA高级语法

    高级语法 第三章:面向对象和高级语法 实例化: 不实例化,就是一个空指针 注意,声明和实例化是两个过程.声明的过程是不分配内存空间的,只有实例化才会真正分配空间 对变量的分类 实例变量只有实例化之后才 ...

  4. celery 分布式异步队列框架使用方法

    简介: Celery  是一个python开发的异步分布式任务调度模块,是一个消息传输的中间件,可以理解为一个邮箱,每当应用程序调用celery的异步任务时,会向broker传递消息,然后celery ...

  5. PHP 网站大数据大流量与高并发 笔记

    前端: 1.域名开启cdn 2.大文件使用oss php: 1.模板编译缓存 服务器: 1.负载均衡 数据库: 1.读写分离 待完善

  6. 北上广Java开发月薪20K往上,该如何做,需要会写什么

    这个问题可能很多人会说这只是大企业或者互联网企业工程师才能拿到.也许是的,小公司或者非互联网企业拿两万的不太可能是码农了,应该已经转管理.还有区域问题,这个不在我的考虑范围内,因为这方面除了北上广深杭 ...

  7. yii自定义验证

    自定义验证类 class BaseModel extends Model { public function rules() { return [ ['obj', ContentSecurityVal ...

  8. console的各种用法

    console的各种用法 1.输出信息 console.log('消息内容!'); //输出普通信息 console.info('消息内容!'); //输出提示信息 (在ie上有区分) console ...

  9. Hadoop网页监控配置

    接之前的内容http://www.cnblogs.com/jourluohua/p/8734406.html 在之前那的内容中,仅实现了Hadoop的安装和运行,距离实际使用还有很远.现在先完成一个小 ...

  10. Spingboot使用log4j2

    1.pom.xml加入log4j2,并同时把spring boot默认的logging去掉,注意一定要全部排除否则会报错. <dependency> <groupId>org. ...