效果图:

代码区:

package com.wls.integrateplugs.datasource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; @Configuration
public class DataSourceConfig {
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@Primary
@ConfigurationProperties(prefix="spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
} @Bean(name = "primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(
@Qualifier("primaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name = "secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(
@Qualifier("secondaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}

  

package com.wls.integrateplugs.jpa.primary.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map; @Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactoryPrimary",
transactionManagerRef="transactionManagerPrimary",
basePackages= { "com.wls.integrateplugs.jpa.primary.repository" }) //设置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.wls.integrateplugs.jpa.primary.model") //设置实体类所在位置
.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());
} }

  

package com.wls.integrateplugs.jpa.second.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map; @Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactorySecondary",
transactionManagerRef="transactionManagerSecondary",
basePackages= { "com.wls.integrateplugs.jpa.second.reposity" }) //设置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.wls.integrateplugs.jpa.second.model") //设置实体类所在位置
.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());
} }

  

package com.wls.integrateplugs.jpa.primary.model;

/**
* Created by wls on 2017/8/24.
*/
import java.io.Serializable; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id; @Entity
public class User implements Serializable { private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String userName;
@Column(nullable = false)
private String passWord;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = true, unique = true)
private String nickName;
@Column(nullable = false)
private String regTime;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private Integer age; public User() {
super();
} public User(String name, Integer age) {
this.name = name;
this.age = age;
} public User(String userName, String passWord, String email, String nickName, String regTime, String name, Integer age) {
this.userName = userName;
this.passWord = passWord;
this.email = email;
this.nickName = nickName;
this.regTime = regTime;
this.name = name;
this.age = age;
} public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getRegTime() {
return regTime;
}
public void setRegTime(String regTime) {
this.regTime = regTime;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
}
}

  

package com.wls.integrateplugs.jpa.second.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id; /**
* @author 程序猿DD
* @version 1.0.0
* @date 16/3/21 下午3:35.
* @blog http://blog.didispace.com
*/
@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;
} public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
} }

  

package com.wls.integrateplugs.jpa.primary.repository;

import com.wls.integrateplugs.jpa.primary.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; /**
* @author 程序猿DD
* @version 1.0.0
* @date 16/3/23 下午2:34.
* @blog http://blog.didispace.com
*/
public interface UserRepository extends JpaRepository<User, Long> { User findByName(String name); User findByNameAndAge(String name, Integer age); @Query("from User u where u.name=:name")
User findUser(@Param("name") String name);
}

  

package com.wls.integrateplugs.jpa.second.reposity;

import com.wls.integrateplugs.jpa.second.model.Message;
import org.springframework.data.jpa.repository.JpaRepository; /**
* @author 程序猿DD
* @version 1.0.0
* @date 16/3/23 下午2:34.
* @blog http://blog.didispace.com
*/
public interface MessageRepository extends JpaRepository<Message, Long> { }

  

package com.wls.test.integrateplugs.jpa;

import com.wls.integrateplugs.jpa.primary.model.User;
import com.wls.integrateplugs.jpa.primary.repository.UserRepository;
import com.wls.integrateplugs.jpa.second.model.Message;
import com.wls.integrateplugs.jpa.second.reposity.MessageRepository;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class JpaTest { @Autowired
private UserRepository userRepository;
@Autowired
private MessageRepository messageRepository; @Before
public void setUp() {
} @Test
public void test() throws Exception { userRepository.save(new User("aa","aa","aa","aa","aa","aa",12));
userRepository.save(new User("bb","bb","bb","bb","bb","bb",13));
userRepository.save(new User("cc","cc","cc","cc","cc","cc",14)); Assert.assertEquals(3, 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:
datasource:
primary:
driver-class-name: com.mysql.jdbc.Driver
# url: jdbc:mysql://192.168.159.128:3306/mydb
url: jdbc:mysql://192.168.223.128:3306/db1
username: wls
password: Wls141215!
secondary:
driver-class-name: com.mysql.jdbc.Driver
# url: jdbc:mysql://192.168.159.128:3306/mydb
url: jdbc:mysql://192.168.223.128:3306/db2
username: wls
password: Wls141215!
jpa:
hibernate:
ddl-auto: update
show-sql: true

  

  <!--    jpa     -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

  

Spring Boot☞ 多数据源配置(二):Spring-data-jpa的更多相关文章

  1. Spring Boot多数据源配置(二)MongoDB

    在Spring Boot多数据源配置(一)durid.mysql.jpa 整合中已经讲过了Spring Boot如何配置mysql多数据源.本篇文章讲一下Spring Boot如何配置mongoDB多 ...

  2. spring boot多数据源配置(mysql,redis,mongodb)实战

    使用Spring Boot Starter提升效率 虽然不同的starter实现起来各有差异,但是他们基本上都会使用到两个相同的内容:ConfigurationProperties和AutoConfi ...

  3. spring boot 多数据源配置与使用

    在介绍使用JdbcTemplate和Spring-data-jpa时,都使用了单数据源.在单数据源的情况下,Spring Boot的配置非常简单,只需要在application.properties文 ...

  4. spring boot(12)-数据源配置原理

    本篇讲的不仅是数据源配置,这也是spring boot实现自动配置的一部分.要理解数据源的配置原理,首先要理解第十篇tomcat连接池的配置 数据源配置源码 这里截取org.springframewo ...

  5. 21. Spring Boot Druid 数据源配置解析

    1.数据源配置属性类源码 package org.springframework.boot.autoconfigure.jdbc; @ConfigurationProperties( prefix = ...

  6. 三、Spring Boot 多数据源配置

    下面一个Java类是已经写好的根据配置文件动态创建多dataSource的代码,其原理也很简单,就是读取配置文件,根据配置文件中配置的数据源数量,动态创建dataSource并注册到Spring中. ...

  7. Spring Boot Druid数据源配置

    package com.hgvip.config; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.su ...

  8. Spring Boot多数据源配置与使用

    在单数据源的情况下,Spring Boot的配置非常简单,只需要在application.properties文件中配置连接参数即可.但是往往随着业务量发展,我们通常会进行数据库拆分或是引入其他数据库 ...

  9. Spring Boot (14) 数据源配置原理

    数据源配置源码 这里截取org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration的部分源码,主要介绍Tomcat和Hika ...

随机推荐

  1. 1、Window.document对象

    1.Window.document对象 一.找到元素: docunment.getElementById("id"):根据id找,最多找一个:    var a =docunmen ...

  2. AngularJS.js: temple

    ylbtech-AngularJS.js: temple 1.返回顶部   2.返回顶部   3.返回顶部   4.返回顶部   5.返回顶部     6.返回顶部   7.返回顶部   8.返回顶部 ...

  3. Maven的学习

    Maven是Apache的一个项目,它使用对象模型(POM),可以通过一小段描述信息来管理项目的构建,报告和文档的软件项目管理工具.它集项目的构建,清理,编译等于一体,以前我们在使用IDE时,基本上一 ...

  4. Oracle block 格式

    Oracle block 格式 信息参考:  http://www.ixora.com.au/ 特别感谢 overtime 大哥对我的无私的帮助和对我一直鼓励支持我的网友这些资料是没得到oracle ...

  5. mysql where语句中 or 和 and连用注意点

    在mysql中,经常会遇到这样的情况,在写条件语句where时,可能会同时有多个条件的“或”或者“与”,但经常会达不到效果,经百度,本人发现一个where语句中同时出现条件的“与”或者“或的时候”,要 ...

  6. Linux 服务器--Iptables 端口转发

    日常Iptables 端口转发 需求:公司是局域网络,通过一个外网ip,进行互联网的访问.公司的云平台服务器在公网中,虚拟化平台中有一台内部服务器,用于公司某部门的使用,上面运行www 服务,ssh端 ...

  7. 启动Eclipse之后,关闭Maven自动更新

    问题描述: 因为架包的修改,所以Maven需要更新,一启动Eclipse之后,自动更新,由于Maven的架包很多download不下来,就一直卡着的样子,很长时间,什么都做不了. 解决办法: Ecli ...

  8. SuggestFrameWork js代码结构

    关于suggestFrameWork的使用教程网上很多,如果您仅仅想知道如何使用请移步.这里展现一下js代码实现结构 下载地址 http://sourceforge.net/projects/sugg ...

  9. JavaScript知识总结--对象的相关概念

    一.定义 无序属性的集合. 说白了就是一个容器,可以容纳[基本值.对象或者函数],这些东西都叫做属性.每个属性都有一个名字,每个名字都映射一个值(可以是基本类型的值,也可以是引用类型的值).从以上描述 ...

  10. Rhythmk 一步一步学 JAVA (15) mybatis 入门学习-1

    1.mybatis 通过mybatis-generator-core-1.3.2 代码生成: 工具下载地址: https://code.google.com/p/mybatis/ 解压工具包 myba ...