http://www.ityouknow.com/springboot/2016/08/20/springboot(%E4%BA%94)-spring-data-jpa%E7%9A%84%E4%BD%BF%E7%94%A8.html

http://www.cnblogs.com/shihuc/p/5169418.html 这个不错

https://medium.com/@joeclever/using-multiple-datasources-with-spring-boot-and-spring-data-6430b00c02e7

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html

https://stackoverflow.com/questions/44507705/spring-boot-connect-mysql-and-mongodb

同源数据库的多源支持

日常项目中因为使用的分布式开发模式,不同的服务有不同的数据源,常常需要在一个项目中使用多个数据源,因此需要配置sping data jpa对多数据源的使用,一般分一下为三步:

  • 1 配置多数据源
  • 2 不同源的实体类放入不同包路径
  • 3 声明不同的包路径下使用不同的数据源、事务支持

这里有一篇文章写的很清楚:Spring Boot多数据源配置与使用

异构数据库多源支持

比如我们的项目中,即需要对mysql的支持,也需要对mongodb的查询等。

实体类声明@Entity 关系型数据库支持类型、声明@Document 为mongodb支持类型,不同的数据源使用不同的实体就可以了

interface PersonRepository extends Repository<Person, Long> {

} @Entity
public class Person {

} interface UserRepository extends Repository<User, Long> {

} @Document
public class User {

}

但是,如果User用户既使用mysql也使用mongodb呢,也可以做混合使用

interface JpaPersonRepository extends Repository<Person, Long> {

} interface MongoDBPersonRepository extends Repository<Person, Long> {

} @Entity
@Document
public class Person {

}

也可以通过对不同的包路径进行声明,比如A包路径下使用mysql,B包路径下使用mongoDB

@EnableJpaRepositories(basePackages = "com.neo.repositories.jpa")
@EnableMongoRepositories(basePackages = "com.neo.repositories.mongo")
interface Configuration { }

http://www.jianshu.com/p/34730e595a8c

http://www.cnblogs.com/liujiduo/p/5004691.html

___________________________________

http://limingnihao.iteye.com/blog/1940446

MongoDB整合Spring

(黎明你好原创作品,转载请注明)

4.1 创建maven项目

4.1.1 repositories

创建maven项目,其中repositories使用spring的maven库:

  1. <repositories>
  2. <repository>
  3. <id>central</id>
  4. <name>Maven Central</name>
  5. <url>http://repo1.maven.org/maven2/</url>
  6. </repository>
  7. <repository>
  8. <id>spring-release</id>
  9. <name>Spring Maven Release Repository</name>
  10. <url>http://repo.springsource.org/libs-release</url>
  11. </repository>
  12. <repository>
  13. <id>atlassian-m2-repository</id>
  14. <url>https://m2proxy.atlassian.com/repository/public</url>
  15. </repository>
  16. </repositories>

4.1.2 Dependencies

使用到的jar包:

  1. <dependencies>
  2. <dependency>
  3. <groupId>javax.servlet</groupId>
  4. <artifactId>servlet-api</artifactId>
  5. <version>2.5</version>
  6. <type>jar</type>
  7. <scope>provided</scope>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.slf4j</groupId>
  11. <artifactId>slf4j-api</artifactId>
  12. <version>1.6.1</version>
  13. <type>jar</type>
  14. <scope>compile</scope>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.slf4j</groupId>
  18. <artifactId>slf4j-log4j12</artifactId>
  19. <version>1.7.5</version>
  20. <type>jar</type>
  21. <scope>runtime</scope>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.mongodb</groupId>
  25. <artifactId>mongo-java-driver</artifactId>
  26. <version>2.10.1</version>
  27. <type>jar</type>
  28. <scope>compile</scope>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.data</groupId>
  32. <artifactId>spring-data-mongodb</artifactId>
  33. <version>1.2.1.RELEASE</version>
  34. <type>jar</type>
  35. <scope>compile</scope>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework.data</groupId>
  39. <artifactId>spring-data-mongodb-cross-store</artifactId>
  40. <version>1.2.1.RELEASE</version>
  41. <type>jar</type>
  42. <scope>compile</scope>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.springframework.data</groupId>
  46. <artifactId>spring-data-mongodb-log4j</artifactId>
  47. <version>1.2.1.RELEASE</version>
  48. <type>jar</type>
  49. <scope>compile</scope>
  50. </dependency>
  51. </dependencies>

4.2 添加spring配置文件

spring的配置文件applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mongo="http://www.springframework.org/schema/data/mongo"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/data/mongo
  9. http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  12. <context:component-scan base-package="liming.mongodb.example" />
  13. <mongo:mongo host="127.0.0.1" port="27017" />
  14. <!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
  15. <mongo:db-factory dbname="student" mongo-ref="mongo" />
  16. <!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 -->
  17. <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
  18. <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
  19. </bean>
  20. <!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 -->
  21. <mongo:mapping-converter base-package="climing.mongodb.example.data.model" />
  22. <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
  23. <mongo:repositories base-package="liming.mongodb.example.data.impl" />
  24. <context:annotation-config />
  25. </beans>

4.3 增删改查

Userl实现的增删改查:

4.3.1UserEntity

  1. package liming.mongodb.example.data.model;
  2. import java.util.Date;
  3. import org.springframework.data.annotation.Id;
  4. import org.springframework.data.mongodb.core.mapping.Document;
  5. @Document(collection = "user")
  6. public class UserEntity {
  7. @Id
  8. private String id;
  9. private NameEntity name;
  10. private int age;
  11. private int works;
  12. private Date birth;
  13. private String password;
  14. private String regionName;
  15. private String[] special;
  16. public String getId() {
  17. return id;
  18. }
  19. public void setId(String id) {
  20. this.id = id;
  21. }
  22. public NameEntity getName() {
  23. return name;
  24. }
  25. public void setName(NameEntity name) {
  26. this.name = name;
  27. }
  28. public int getAge() {
  29. return age;
  30. }
  31. public void setAge(int age) {
  32. this.age = age;
  33. }
  34. public int getWorks() {
  35. return works;
  36. }
  37. public void setWorks(int works) {
  38. this.works = works;
  39. }
  40. public Date getBirth() {
  41. return birth;
  42. }
  43. public void setBirth(Date birth) {
  44. this.birth = birth;
  45. }
  46. public String getPassword() {
  47. return password;
  48. }
  49. public void setPassword(String password) {
  50. this.password = password;
  51. }
  52. public String getRegionName() {
  53. return regionName;
  54. }
  55. public void setRegionName(String regionName) {
  56. this.regionName = regionName;
  57. }
  58. public String[] getSpecial() {
  59. return special;
  60. }
  61. public void setSpecial(String[] special) {
  62. this.special = special;
  63. }
  64. }

4.3.2 NameEntity

  1. package liming.mongodb.example.data.model;
  2. public class NameEntity {
  3. private String username;
  4. private String nickname;
  5. public String getUsername() {
  6. return username;
  7. }
  8. public void setUsername(String username) {
  9. this.username = username;
  10. }
  11. public String getNickname() {
  12. return nickname;
  13. }
  14. public void setNickname(String nickname) {
  15. this.nickname = nickname;
  16. }
  17. }

4.3.3 UserDao

  1. package liming.mongodb.example.data;
  2. import java.util.List;
  3. import liming.mongodb.example.data.model.UserEntity;
  4. import org.springframework.transaction.annotation.Transactional;
  5. @Transactional
  6. public interface UserDao {
  7. public abstract void _test();
  8. public abstract void createCollection();
  9. public abstract List<UserEntity> findList(int skip, int limit);
  10. public abstract List<UserEntity> findListByAge(int age);
  11. public abstract UserEntity findOne(String id);
  12. public abstract UserEntity findOneByUsername(String username);
  13. public abstract void insert(UserEntity entity);
  14. public abstract void update(UserEntity entity);
  15. }

4.3.4 UserDaoImpl

  1. package liming.mongodb.example.data.impl;
  2. import java.util.List;
  3. import java.util.Set;
  4. import liming.mongodb.example.data.UserDao;
  5. import liming.mongodb.example.data.model.UserEntity;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.data.domain.Sort;
  10. import org.springframework.data.domain.Sort.Direction;
  11. import org.springframework.data.domain.Sort.Order;
  12. import org.springframework.data.mongodb.core.MongoTemplate;
  13. import org.springframework.data.mongodb.core.query.Criteria;
  14. import org.springframework.data.mongodb.core.query.Query;
  15. import org.springframework.data.mongodb.core.query.Update;
  16. import org.springframework.stereotype.Repository;
  17. import com.mongodb.DB;
  18. @Repository
  19. public class UserDaoImpl implements UserDao {
  20. public static final Logger logger = LoggerFactory.getLogger(UserDaoImpl.class);
  21. @Autowired
  22. private MongoTemplate mongoTemplate;
  23. @Override
  24. public void _test() {
  25. Set<String> colls = this.mongoTemplate.getCollectionNames();
  26. for (String coll : colls) {
  27. logger.info("CollectionName=" + coll);
  28. }
  29. DB db = this.mongoTemplate.getDb();
  30. logger.info("db=" + db.toString());
  31. }
  32. @Override
  33. public void createCollection() {
  34. if (!this.mongoTemplate.collectionExists(UserEntity.class)) {
  35. this.mongoTemplate.createCollection(UserEntity.class);
  36. }
  37. }
  38. @Override
  39. public List<UserEntity> findList(int skip, int limit) {
  40. Query query = new Query();
  41. query.with(new Sort(new Order(Direction.ASC, "_id")));
  42. query.skip(skip).limit(limit);
  43. return this.mongoTemplate.find(query, UserEntity.class);
  44. }
  45. @Override
  46. public List<UserEntity> findListByAge(int age) {
  47. Query query = new Query();
  48. query.addCriteria(new Criteria("age").is(age));
  49. return this.mongoTemplate.find(query, UserEntity.class);
  50. }
  51. @Override
  52. public UserEntity findOne(String id) {
  53. Query query = new Query();
  54. query.addCriteria(new Criteria("_id").is(id));
  55. return this.mongoTemplate.findOne(query, UserEntity.class);
  56. }
  57. @Override
  58. public UserEntity findOneByUsername(String username) {
  59. Query query = new Query();
  60. query.addCriteria(new Criteria("name.username").is(username));
  61. return this.mongoTemplate.findOne(query, UserEntity.class);
  62. }
  63. @Override
  64. public void insert(UserEntity entity) {
  65. this.mongoTemplate.insert(entity);
  66. }
  67. @Override
  68. public void update(UserEntity entity) {
  69. Query query = new Query();
  70. query.addCriteria(new Criteria("_id").is(entity.getId()));
  71. Update update = new Update();
  72. update.set("age", entity.getAge());
  73. update.set("password", entity.getPassword());
  74. update.set("regionName", entity.getRegionName());
  75. update.set("special", entity.getSpecial());
  76. update.set("works", entity.getWorks());
  77. update.set("name", entity.getName());
  78. this.mongoTemplate.updateFirst(query, update, UserEntity.class);
  79. }
  80. }

4.3.5 测试代码

  1. package liming.mongodb.example;
  2. import java.util.Arrays;
  3. import java.util.Date;
  4. import java.util.List;
  5. import liming.mongodb.example.data.UserDao;
  6. import liming.mongodb.example.data.impl.UserDaoImpl;
  7. import liming.mongodb.example.data.model.UserEntity;
  8. import org.springframework.context.ConfigurableApplicationContext;
  9. import org.springframework.context.support.ClassPathXmlApplicationContext;
  10. public class ApplicationSpring {
  11. public static void main(String[] args) {
  12. System.out.println("Bootstrapping HelloMongo");
  13. ConfigurableApplicationContext context = null;
  14. context = new ClassPathXmlApplicationContext("applicationContext.xml");
  15. UserDao userDao = context.getBean(UserDaoImpl.class);
  16. userDao._test();
  17. UserEntity entity1 = new UserEntity();
  18. entity1.setId("5");
  19. entity1.setAge(1);
  20. entity1.setBirth(new Date());
  21. entity1.setPassword("asdfasdf");
  22. entity1.setRegionName("北京");
  23. entity1.setWorks(1);
  24. userDao.insert(entity1);
  25. userDao.update(entity1);
  26. userDao.createCollection();
  27. List<UserEntity> list = userDao.findList(0, 10);
  28. for (UserEntity e : list) {
  29. System.out.println("all - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special=" + Arrays.toString(e.getSpecial())
  30. + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
  31. }
  32. list = userDao.findListByAge(1);
  33. for (UserEntity e : list) {
  34. System.out.println("age=1 - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special="
  35. + Arrays.toString(e.getSpecial()) + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
  36. }
  37. UserEntity e = userDao.findOne("1");
  38. System.out.println("id=1 - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special=" + Arrays.toString(e.getSpecial())
  39. + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
  40. e = userDao.findOneByUsername("limingnihao");
  41. System.out.println("username=limingnihao - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special="
  42. + Arrays.toString(e.getSpecial()) + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
  43. System.out.println("DONE!");
  44. }
  45. }

spring 中连接多个数据源的更多相关文章

  1. spring boot 连接多个数据源

    在springboot中有需要连接多个数据源的情况. 首先配置文件application.properties中添加两个数据源连接字符串 mybatis.type-aliases-package=co ...

  2. 关于32位程序在Win7&64位系统中连接Microsoft Excel数据源的问题

    最近在新公司电脑上跑以前的selenium测试框架的时候,抛出了如下的错误 出现的是ODBC Driver问题:[Microsoft][ODBC Driver Manager] Data source ...

  3. spring中连接池的配置

    在默认通过myeclipse生成的配置里,spring使用的是apache的dbcp连接池 <bean id="dataSource" class="org.apa ...

  4. 在Spring中配置SQL server 2000

    前言 Lz主要目的是在Spring中配置SQL server 2000数据库,但实现目的的过程中参差着许多SQL server 2000的知识,也包罗在本文记载下来!(Lz为什么要去搞sql serv ...

  5. Spring中配置数据源的4种形式

    不管采用何种持久化技术,都需要定义数据源.Spring中提供了4种不同形式的数据源配置方式: spring自带的数据源(DriverManagerDataSource),DBCP数据源,C3P0数据源 ...

  6. C3P0连接池在hibernate和spring中的配置

    首先为什么要使用连接池及为什么要选择C3P0连接池,这里就不多说了,目前C3P0连接池还是比较方便.比较稳定的连接池,能与spring.hibernate等开源框架进行整合. 一.hibernate中 ...

  7. Spring中配置数据源的4种形式(转)

    原文http://blog.csdn.net/orclight/article/details/8616103       不管采用何种持久化技术,都需要定义数据源.Spring中提供了4种不同形式的 ...

  8. Spring中配置数据源的四种方式

    1.spring自带的数据源 <bean id="dataSource" class="org.springframework.jdbc.datasource.Dr ...

  9. Spring中配置数据源常用的形式

    不管采用何种持久化技术,都需要定义数据源.Spring中提供了4种不同形式的数据源配置方式: spring自带的数据源(DriverManagerDataSource),DBCP数据源,C3P0数据源 ...

随机推荐

  1. bnu——GCD SUM (莫比乌斯反演)

    题目:GCD SUM 题目链接:http://www.bnuoj.com/v3/problem_show.php?pid=39872 算法:莫比乌斯反演.优化 #include<stdio.h& ...

  2. jQuery的each使用陷阱

    注意:jQuery使用each()函数进行循环时发现return false不能阻止程序继续向下执行 原因如下: (1)开始还以为是jQuery的each()函数是异步执行的,所以导致出错,其实不是. ...

  3. MyBatis SpringBoot 杂记

    最近接了个xxx代码. 不能说人家不好, 因为必进年月久了.能用这么长时间, 不就说明还不错么?! 我们现在每天写的, 能超出人家的么~~~ 呵呵 Java项目中, 把动态数据源切换的框架整合进来. ...

  4. Apache ab 单测 分布式

    使用synchronized 处理并发 缺点:无法做到细粒度控制 只适合单点的情况 使用Redis作为分布式锁 setnx命令 设计模式 :使用 !setnx 加锁 getset命令

  5. MySQL 5.7 关闭严格模式

    If your app was written for older versions of MySQL and is not compatible with strict SQL mode in My ...

  6. JavaScript 使用 toJSON 方法格式化日期

    toJSON 方法可以将 Date 对象转换为 ISO-8601 标准的字符串:YYYY-MM-DDTHH:mm:ss. sssZ var date = new Date(); // toJSON() ...

  7. Xml文件汉化准备

    如何提取xml文件中的字符串,是汉化的前提. Passolo中的解析器不能正确解析文件,此时可以采用Text Parser进行解析. 通过自定义规则,可以相对完整的把字符串提取出来. 一张图片就能说明 ...

  8. Vmware 给虚拟机传脚本并执行

    #_*_ coding:utf8 _*_ from pysphere import VIServer import ssl import re import sys import os import ...

  9. P1282 多米诺骨牌 dp

    思路:dp[i][j] 的j是上半段的和的值   这里表示的是达到上半段值是j的最小次数 答案在最小的可达到的j #include<bits/stdc++.h> using namespa ...

  10. codechef EBAIT Election Bait【欧几里得算法】

    题目分析: 欧几里得算法来处理一类分数问题,分数问题的形式如下 $\frac{a}{b} < \frac{p}{q} < \frac{c}{d}$ 当a=0时,答案等于$\frac{1}{ ...