spring 中连接多个数据源
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库:
- <repositories>
- <repository>
- <id>central</id>
- <name>Maven Central</name>
- <url>http://repo1.maven.org/maven2/</url>
- </repository>
- <repository>
- <id>spring-release</id>
- <name>Spring Maven Release Repository</name>
- <url>http://repo.springsource.org/libs-release</url>
- </repository>
- <repository>
- <id>atlassian-m2-repository</id>
- <url>https://m2proxy.atlassian.com/repository/public</url>
- </repository>
- </repositories>
4.1.2 Dependencies
使用到的jar包:
- <dependencies>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.5</version>
- <type>jar</type>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.6.1</version>
- <type>jar</type>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>1.7.5</version>
- <type>jar</type>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>org.mongodb</groupId>
- <artifactId>mongo-java-driver</artifactId>
- <version>2.10.1</version>
- <type>jar</type>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-mongodb</artifactId>
- <version>1.2.1.RELEASE</version>
- <type>jar</type>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-mongodb-cross-store</artifactId>
- <version>1.2.1.RELEASE</version>
- <type>jar</type>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-mongodb-log4j</artifactId>
- <version>1.2.1.RELEASE</version>
- <type>jar</type>
- <scope>compile</scope>
- </dependency>
- </dependencies>
4.2 添加spring配置文件
spring的配置文件applicationContext.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mongo="http://www.springframework.org/schema/data/mongo"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/data/mongo
- http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <context:component-scan base-package="liming.mongodb.example" />
- <mongo:mongo host="127.0.0.1" port="27017" />
- <!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
- <mongo:db-factory dbname="student" mongo-ref="mongo" />
- <!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 -->
- <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
- <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
- </bean>
- <!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 -->
- <mongo:mapping-converter base-package="climing.mongodb.example.data.model" />
- <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
- <mongo:repositories base-package="liming.mongodb.example.data.impl" />
- <context:annotation-config />
- </beans>
4.3 增删改查
Userl实现的增删改查:
4.3.1UserEntity
- package liming.mongodb.example.data.model;
- import java.util.Date;
- import org.springframework.data.annotation.Id;
- import org.springframework.data.mongodb.core.mapping.Document;
- @Document(collection = "user")
- public class UserEntity {
- @Id
- private String id;
- private NameEntity name;
- private int age;
- private int works;
- private Date birth;
- private String password;
- private String regionName;
- private String[] special;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public NameEntity getName() {
- return name;
- }
- public void setName(NameEntity name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public int getWorks() {
- return works;
- }
- public void setWorks(int works) {
- this.works = works;
- }
- public Date getBirth() {
- return birth;
- }
- public void setBirth(Date birth) {
- this.birth = birth;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getRegionName() {
- return regionName;
- }
- public void setRegionName(String regionName) {
- this.regionName = regionName;
- }
- public String[] getSpecial() {
- return special;
- }
- public void setSpecial(String[] special) {
- this.special = special;
- }
- }
4.3.2 NameEntity
- package liming.mongodb.example.data.model;
- public class NameEntity {
- private String username;
- private String nickname;
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getNickname() {
- return nickname;
- }
- public void setNickname(String nickname) {
- this.nickname = nickname;
- }
- }
4.3.3 UserDao
- package liming.mongodb.example.data;
- import java.util.List;
- import liming.mongodb.example.data.model.UserEntity;
- import org.springframework.transaction.annotation.Transactional;
- @Transactional
- public interface UserDao {
- public abstract void _test();
- public abstract void createCollection();
- public abstract List<UserEntity> findList(int skip, int limit);
- public abstract List<UserEntity> findListByAge(int age);
- public abstract UserEntity findOne(String id);
- public abstract UserEntity findOneByUsername(String username);
- public abstract void insert(UserEntity entity);
- public abstract void update(UserEntity entity);
- }
4.3.4 UserDaoImpl
- package liming.mongodb.example.data.impl;
- import java.util.List;
- import java.util.Set;
- import liming.mongodb.example.data.UserDao;
- import liming.mongodb.example.data.model.UserEntity;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.domain.Sort;
- import org.springframework.data.domain.Sort.Direction;
- import org.springframework.data.domain.Sort.Order;
- import org.springframework.data.mongodb.core.MongoTemplate;
- import org.springframework.data.mongodb.core.query.Criteria;
- import org.springframework.data.mongodb.core.query.Query;
- import org.springframework.data.mongodb.core.query.Update;
- import org.springframework.stereotype.Repository;
- import com.mongodb.DB;
- @Repository
- public class UserDaoImpl implements UserDao {
- public static final Logger logger = LoggerFactory.getLogger(UserDaoImpl.class);
- @Autowired
- private MongoTemplate mongoTemplate;
- @Override
- public void _test() {
- Set<String> colls = this.mongoTemplate.getCollectionNames();
- for (String coll : colls) {
- logger.info("CollectionName=" + coll);
- }
- DB db = this.mongoTemplate.getDb();
- logger.info("db=" + db.toString());
- }
- @Override
- public void createCollection() {
- if (!this.mongoTemplate.collectionExists(UserEntity.class)) {
- this.mongoTemplate.createCollection(UserEntity.class);
- }
- }
- @Override
- public List<UserEntity> findList(int skip, int limit) {
- Query query = new Query();
- query.with(new Sort(new Order(Direction.ASC, "_id")));
- query.skip(skip).limit(limit);
- return this.mongoTemplate.find(query, UserEntity.class);
- }
- @Override
- public List<UserEntity> findListByAge(int age) {
- Query query = new Query();
- query.addCriteria(new Criteria("age").is(age));
- return this.mongoTemplate.find(query, UserEntity.class);
- }
- @Override
- public UserEntity findOne(String id) {
- Query query = new Query();
- query.addCriteria(new Criteria("_id").is(id));
- return this.mongoTemplate.findOne(query, UserEntity.class);
- }
- @Override
- public UserEntity findOneByUsername(String username) {
- Query query = new Query();
- query.addCriteria(new Criteria("name.username").is(username));
- return this.mongoTemplate.findOne(query, UserEntity.class);
- }
- @Override
- public void insert(UserEntity entity) {
- this.mongoTemplate.insert(entity);
- }
- @Override
- public void update(UserEntity entity) {
- Query query = new Query();
- query.addCriteria(new Criteria("_id").is(entity.getId()));
- Update update = new Update();
- update.set("age", entity.getAge());
- update.set("password", entity.getPassword());
- update.set("regionName", entity.getRegionName());
- update.set("special", entity.getSpecial());
- update.set("works", entity.getWorks());
- update.set("name", entity.getName());
- this.mongoTemplate.updateFirst(query, update, UserEntity.class);
- }
- }
4.3.5 测试代码
- package liming.mongodb.example;
- import java.util.Arrays;
- import java.util.Date;
- import java.util.List;
- import liming.mongodb.example.data.UserDao;
- import liming.mongodb.example.data.impl.UserDaoImpl;
- import liming.mongodb.example.data.model.UserEntity;
- import org.springframework.context.ConfigurableApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class ApplicationSpring {
- public static void main(String[] args) {
- System.out.println("Bootstrapping HelloMongo");
- ConfigurableApplicationContext context = null;
- context = new ClassPathXmlApplicationContext("applicationContext.xml");
- UserDao userDao = context.getBean(UserDaoImpl.class);
- userDao._test();
- UserEntity entity1 = new UserEntity();
- entity1.setId("5");
- entity1.setAge(1);
- entity1.setBirth(new Date());
- entity1.setPassword("asdfasdf");
- entity1.setRegionName("北京");
- entity1.setWorks(1);
- userDao.insert(entity1);
- userDao.update(entity1);
- userDao.createCollection();
- List<UserEntity> list = userDao.findList(0, 10);
- for (UserEntity e : list) {
- System.out.println("all - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special=" + Arrays.toString(e.getSpecial())
- + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
- }
- list = userDao.findListByAge(1);
- for (UserEntity e : list) {
- System.out.println("age=1 - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special="
- + Arrays.toString(e.getSpecial()) + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
- }
- UserEntity e = userDao.findOne("1");
- System.out.println("id=1 - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special=" + Arrays.toString(e.getSpecial())
- + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
- e = userDao.findOneByUsername("limingnihao");
- System.out.println("username=limingnihao - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special="
- + Arrays.toString(e.getSpecial()) + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
- System.out.println("DONE!");
- }
- }
spring 中连接多个数据源的更多相关文章
- spring boot 连接多个数据源
在springboot中有需要连接多个数据源的情况. 首先配置文件application.properties中添加两个数据源连接字符串 mybatis.type-aliases-package=co ...
- 关于32位程序在Win7&64位系统中连接Microsoft Excel数据源的问题
最近在新公司电脑上跑以前的selenium测试框架的时候,抛出了如下的错误 出现的是ODBC Driver问题:[Microsoft][ODBC Driver Manager] Data source ...
- spring中连接池的配置
在默认通过myeclipse生成的配置里,spring使用的是apache的dbcp连接池 <bean id="dataSource" class="org.apa ...
- 在Spring中配置SQL server 2000
前言 Lz主要目的是在Spring中配置SQL server 2000数据库,但实现目的的过程中参差着许多SQL server 2000的知识,也包罗在本文记载下来!(Lz为什么要去搞sql serv ...
- Spring中配置数据源的4种形式
不管采用何种持久化技术,都需要定义数据源.Spring中提供了4种不同形式的数据源配置方式: spring自带的数据源(DriverManagerDataSource),DBCP数据源,C3P0数据源 ...
- C3P0连接池在hibernate和spring中的配置
首先为什么要使用连接池及为什么要选择C3P0连接池,这里就不多说了,目前C3P0连接池还是比较方便.比较稳定的连接池,能与spring.hibernate等开源框架进行整合. 一.hibernate中 ...
- Spring中配置数据源的4种形式(转)
原文http://blog.csdn.net/orclight/article/details/8616103 不管采用何种持久化技术,都需要定义数据源.Spring中提供了4种不同形式的 ...
- Spring中配置数据源的四种方式
1.spring自带的数据源 <bean id="dataSource" class="org.springframework.jdbc.datasource.Dr ...
- Spring中配置数据源常用的形式
不管采用何种持久化技术,都需要定义数据源.Spring中提供了4种不同形式的数据源配置方式: spring自带的数据源(DriverManagerDataSource),DBCP数据源,C3P0数据源 ...
随机推荐
- Tomcat启用GZIP压缩,提升web性能
一.前言 最近做了个项目,遇到这么一个问题:服务器返回给客户端的json数据量太大(大概65M),在客户端加载了1分多钟才渲染完毕,费时耗流量,用户体验极其不好.后来网上搜优化的方法,就是Http压缩 ...
- 1244. Minimum Genetic Mutation
描述 A gene string can be represented by an 8-character long string, with choices from "A", ...
- vue-cli项目开发/生产环境代理实现跨域请求+webpack配置开发/生产环境的接口地址
一.开发环境中跨域 使用 Vue-cli 创建的项目,开发地址是 localhost:8080,需要访问非本机上的接口http://10.1.0.34:8000/queryRole.不同域名之间的访问 ...
- CentOS6.8 安装配置Mysql
1.下载mysql的repo源 wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm 2.安装mysql-commun ...
- Spring Aop实例@Aspect、@Before、@AfterReturning@Around 注解方式配置
用过spring框架进行开发的人,多多少少会使用过它的AOP功能,都知道有@Before.@Around和@After等advice.最近,为了实现项目中的输出日志和权限控制这两个需求,我也使用到了A ...
- jQ append 添加html 及字符串拼接
如图,我要拼接这样一段html: 点击下边添加按钮,不断添加这段Html html: <div class="x_addtable"> <div class=&q ...
- MongoDB学习目录
前面的话 为了能够使用NodeJS实现后端,MongoDB——这个NodeJS标配的数据库就不得不学.小火柴将MongoDB数据库的学习记录整理如下 基础 基础操作 数据类型 文档操作 索引 索引构建 ...
- struts2 核心过滤器的配置
<!-- struts2 过滤器核心配置--> <filter> <filter-name>struts2</filter-name> <filt ...
- Nginx 接受上游缓存流程
L:101 这个指令主要是由上游服务器来决定是否缓存 详见博客Nginx 针对上游服务器缓存
- Jquery实现菜单栏
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8& ...