通过一个数据库的表数据去查询同步另一个数据库,之前的方式是通过写个小工具,然后jdbc方式进行处理,这个方式也挺好用的.学习了springboot后发现可以实现多数据源操作,然后就具体实现以下.

以下代码主要实现的功能有mysql数据的增删改查,oracle数据库的查,还有将mysql数据同步到oracle中.

代码目录结构

java/com.fxust
+config
  -FirstDBConfig.java
  -SecondConfig.java
+controller
  -NoteController.java
  -UserController.java
+dao
  +first
    -UserMapper.java
  +second
    -NoteMapper.java
+model
  +first
    -User.java
  +second
    -Note.java
+service
  +impl
    -NoteServiceImpl.java
    -UserServiceImpl.java
  -NoteService.java
  -UserService.java
-BootApplication
resources
  -application.yml

pom.xml文件的配置情况

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.fxust</groupId>
<artifactId>boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>boot</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

application.yml配置,springboot支持原生的yml配置

server:
port: 8088 //配置启动的端口
//配置mysql数据源
firstDataSource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:/test?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-&useSSL=true
username: root
password: root
//配置oracle数据源
secondDataSource:
driver-class-name: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@127.0.0.1::orcl
username: test
password: test

通过代码获取配置数据源

package com.fxust.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
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 javax.sql.DataSource; /**
* Created by fgq on 2017/12/28.
*/
@Configuration
@MapperScan(basePackages = "com.fxust.dao.first",sqlSessionFactoryRef = "firstSqlSessionFactory")
public class FirstDBConfig { @Bean(name = "firstDataSource")
@ConfigurationProperties(prefix = "firstDataSource")
public DataSource firstDataSource(){
return DataSourceBuilder.create().build();
} @Bean(name = "firstSqlSessionFactory")
public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
}
package com.fxust.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
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 javax.sql.DataSource; /**
* Created by fgq on 2017/12/28.
*/
@Configuration
@MapperScan(basePackages = "com.fxust.dao.second",sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDBConfig { @Bean(name = "secondDataSource")
@ConfigurationProperties(prefix = "secondDataSource")
@Primary
public DataSource secondDataSource(){
return DataSourceBuilder.create().build();
} @Bean(name = "secondSqlSessionFactory")
@Primary
public SqlSessionFactory secondSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
}

基于注解实现dao层的增删改查

package com.fxust.dao.first;

import com.fxust.model.first.User;
import org.apache.ibatis.annotations.*; import java.util.List; /**
* Created by fgq on 2017/12/28.
*/ @Mapper
public interface UserMapper { @Select("select * from user where id = #{id}")
User queryById(@Param("id") int id); @Select("select * from user")
List<User> queryAll(); @Insert({"insert into user(id,name,age,hobby)values(#{id},#{name},#{age},#{hobby})"})
int add(User user); @Update("update user set name=#{name},age=#{age},hobby=#{hobby} where id=#{id}")
int update(User user); @Delete("delete from user where id=#{id}")
int delete(int id);
}
package com.fxust.dao.second;

import com.fxust.model.second.Note;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select; import java.util.List; /**
* Created by fgq on 2017/12/28.
*/
@Mapper
public interface NoteMapper { @Select("select human_id humanId,human_name humanName,human_age humanAge,human_hobby humanHobby,insert_time insertTime from NOTE order by insert_time desc")
List<Note> queryAll(); @Insert("insert into note(human_id,human_name,human_age,human_hobby)values(#{humanId},#{humanName},#{humanAge},#{humanHobby})")
void insert(Note note);
}

model层代码

public class User {
private String id; private String name; private String age; private String hobby;
//省略setter,getter方法
}
public class Note { private int humanId; private String humanName; private int humanAge; private String humanHobby; private String insertTime;
//省略setter,getter方法
}

service层实现业务逻辑

package com.fxust.service.impl;

import com.fxust.dao.first.UserMapper;
import com.fxust.dao.second.NoteMapper;
import com.fxust.model.first.User;
import com.fxust.model.second.Note;
import com.fxust.service.UserSerivce;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; /**
* Created by fgq on 2018/1/12.
*/
@Service
public class UserServiceImpl implements UserSerivce { @Autowired
UserMapper userDao; @Autowired
NoteMapper noteDao; public User queryById(int id){
return userDao.queryById(id);
} public PageInfo<User> queryAllUser(int pageNum, int pageSize){
PageHelper.startPage(pageNum, pageSize);
List<User> userList = userDao.queryAll();
return new PageInfo<>(userList);
} public String addUser(User user){
return userDao.add(user) == 1 ? "success" : "fail";
} public String updateUser(User user){
return userDao.update(user) == 1 ? "success" : "fail";
} public String deleteUser(int id){
return userDao.delete(id) == 1 ? "success" : "fail";
} public void synMysqlToOracle() {
List<User> userList = userDao.queryAll();
for (User user : userList) {
Note note = new Note();
String userId = user.getId();
String userName = user.getName();
String userAge = user.getAge();
String userHobby = user.getHobby();
note.setHumanId(Integer.valueOf(userId));
note.setHumanName(userName);
note.setHumanAge(Integer.valueOf(userAge));
note.setHumanHobby(userHobby);
noteDao.insert(note);
}
}
}
package com.fxust.service.impl;

import com.fxust.dao.second.NoteMapper;
import com.fxust.model.second.Note;
import com.fxust.service.NoteService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; /**
* Created by fgq on 2018/1/12.
*/
@Service
public class NoteServiceImpl implements NoteService { @Autowired
NoteMapper noteDao; public PageInfo<Note> queryAllNote(int pageNum,int pageSize){
PageHelper.startPage(pageNum, pageSize);
List<Note> noteList = noteDao.queryAll();
return new PageInfo<>(noteList);
}
}

controller层实现接口访问控制

package com.fxust.controller;

import com.fxust.model.second.Note;
import com.fxust.service.NoteService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; /**
* Created by fgq on 2017/12/28.
*/
@Controller
@RequestMapping("/note")
public class NoteController { @Autowired
NoteService noteService; //@RequestParam(value = "pageNum",defaultValue = "1") int pageNum, @RequestParam(value = "pageSize",defaultValue = "10") int pageSize
@RequestMapping("queryAll")
@ResponseBody
PageInfo<Note> queryAll(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
return noteService.queryAllNote(pageNum, pageSize);
}
}
package com.fxust.controller;

import com.fxust.model.first.User;
import com.fxust.service.UserSerivce;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; /**
* Created by fengguoqiang on 2017/12/28.
*
*/
@Controller
@RequestMapping(value = "/user")
public class UserController { @Autowired
UserSerivce userSerivce; @RequestMapping(value = "/queryById")
@ResponseBody
User queryById(int id){
return userSerivce.queryById(id);
} @RequestMapping(value = "/queryAll")
@ResponseBody
PageInfo<User> queryAll(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
@RequestParam(value = "pageSize",defaultValue = "10")int pageSize){
return userSerivce.queryAllUser(pageNum, pageSize);
} @RequestMapping(value = "/add")
@ResponseBody
String addUser(User user){
return userSerivce.addUser(user);
} @RequestMapping(value = "/update")
@ResponseBody
String updateUser(User user){
return userSerivce.updateUser(user);
} @RequestMapping(value = "/delete")
@ResponseBody
String delete(int id){
return userSerivce.deleteUser(id);
} @RequestMapping(value = "/syn")
@ResponseBody
void synData(){
userSerivce.synMysqlToOracle();//应该在系统启动后异步执行
} }

调用接口如下

/user/add?name=biadu&age=12&hobby=web

/user/update?name=yahu&age=33&hobby=web&id=2

/user/queryById?id=2

/user/delete?id=1

/user/queryAll

/note/queryAll

SpringBoot实现多数据源(实战源码)的更多相关文章

  1. Spring Boot 揭秘与实战 源码分析 - 工作原理剖析

    文章目录 1. EnableAutoConfiguration 帮助我们做了什么 2. 配置参数类 – FreeMarkerProperties 3. 自动配置类 – FreeMarkerAutoCo ...

  2. Spring Boot 揭秘与实战 源码分析 - 开箱即用,内藏玄机

    文章目录 1. 开箱即用,内藏玄机 2. 总结 3. 源代码 Spring Boot提供了很多”开箱即用“的依赖模块,那么,Spring Boot 如何巧妙的做到开箱即用,自动配置的呢? 开箱即用,内 ...

  3. 详解SpringBoot集成jsp(附源码)+遇到的坑

    本文介绍了SpringBoot集成jsp(附源码)+遇到的坑 ,分享给大家 1.大体步骤 (1)创建Maven web project: (2)在pom.xml文件添加依赖: (3)配置applica ...

  4. SpringBoot事件监听机制源码分析(上) SpringBoot源码(九)

    SpringBoot中文注释项目Github地址: https://github.com/yuanmabiji/spring-boot-2.1.0.RELEASE 本篇接 SpringApplicat ...

  5. CentOS7 实战源码安装mysql5.7.17数据库服务器

    CentOS7 实战源码安装mysql5.7.17数据库服务器 简介:实战演练mysql数据库服务器的搭建  mysql简介: mysql是一个开源的关系型数据库管理系统,现在是oracle公司旗下的 ...

  6. Springboot中mybatis执行逻辑源码分析

    Springboot中mybatis执行逻辑源码分析 在上一篇springboot整合mybatis源码分析已经讲了我们的Mapper接口,userMapper是通过MapperProxy实现的一个动 ...

  7. springboot Properties加载顺序源码分析

    关于properties: 在spring框架中properties为Environment对象重要组成部分, springboot有如下几种种方式注入(优先级从高到低): 1.命令行 java -j ...

  8. 实战 | 源码入门之Faster RCNN

    前言 学习深度学习和计算机视觉,特别是目标检测方向的学习者,一定听说过Faster Rcnn:在目标检测领域,Faster Rcnn表现出了极强的生命力,被大量的学习者学习,研究和工程应用.网上有很多 ...

  9. 学习SpringBoot整合SSM三大框架源码之SpringBoot

    Spring Boot源码剖析 一.Spring Boot 项目的启动入口流程分析 Spring Boot项目的启动入口main线程上有一个@SpringBootApplication( @Confi ...

随机推荐

  1. Openstack深入了解虚拟机

    续Openstack虚拟机创建流程 在控制节点也安装一个计算服务也变成一个计算节点 yum -y install openstack-nova-compute 启动并且设置开机启动 systemctl ...

  2. python3连接Mongodb

    前提条件,安装过Mongondb,并且装一下Robomongo(为了更加直观地看到测试时数据的变化 ) 1.安装PyMySQL pip install pymongo 2.测试 import pymo ...

  3. JDK源码分析之concurrent包(一) -- Executor架构

    Java5新出的concurrent包中的API,是一些并发编程中实用的的工具类.在高并发场景下的使用非常广泛.笔者在这做了一个针对concurrent包中部分常用类的源码分析系列.本系列针对的读者是 ...

  4. 【POJ3615】Cow Hurdles 最短路,你若LCA,我仍不拦你。

    NOIP2013货车运输.仅仅只是数据范围小了很多. 不到150s打完而且AC. . 额.当然.我写的是Floyd. 写LCA的真过分. #include <cstdio> #includ ...

  5. 爬虫任务一:使用httpclient去爬取百度新闻首页的新闻标题和url,编码是utf-8

    第一个入手的爬虫小任务: maven工程 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=" ...

  6. Java读写.properties文件实例,解决中文乱码问题

    package com.lxk.propertyFileTest; import java.io.*; import java.util.Properties; /** * 读写properties文 ...

  7. HDU1838:Chessboard(线性dp)

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=1838 这题也挺不错的.首先题目说了,棋盘的右下角一定是'1',另外棋盘里面至少包含一个1,所以最小值是1, ...

  8. go——基本构成要素

    Go的语言符号又称为词法元素,共包括5类内容: 标识符(identifier) 关键字(keyword) 字面量(literal) 分隔符(delimiter) 操作符(operator)它们可以组成 ...

  9. python报错 TypeError: string indices must be integers

    所以在读取字典的时候,最好先判断类型,然后再查看它是否已经有这样的属性: type(mydict) == type({})             #检查不是字典 如果是字典,再看看有没有这样的属性: ...

  10. HDU - 1695 GCD (容斥+枚举)

    题意:求区间1<=i<=b与区间1<=j<=d之间满足gcd(i,j) = k 的数对 (i,j) 个数.(i,j)与(j,i) 算一个. 分析:gcd(i,j)=k可以转化为 ...