说起多数据源,一般都来解决那些问题呢,主从模式或者业务比较复杂需要连接不同的分库来支持业务。我们项目是后者的模式,网上找了很多,大都是根据jpa来做多数据源解决方案,要不就是老的spring多数据源解决方案,还有的是利用aop动态切换,感觉有点小复杂,其实我只是想找一个简单的多数据支持而已,折腾了两个小时整理出来,供大家参考。

废话不多说直接上代码吧

配置文件

pom包就不贴了比较简单该依赖的就依赖,主要是数据库这边的配置:

mybatis.config-locations=classpath:mybatis/mybatis-config.xml

spring.datasource.test1.driverClassName = com.mysql.jdbc.Driver
spring.datasource.test1.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
spring.datasource.test1.username = root
spring.datasource.test1.password = root spring.datasource.test2.driverClassName = com.mysql.jdbc.Driver
spring.datasource.test2.url = jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8
spring.datasource.test2.username = root
spring.datasource.test2.password = root

一个test1库和一个test2库,其中test1位主库,在使用的过程中必须指定主库,不然会报错。

数据源配置

@Configuration
@MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate")
public class DataSource1Config { @Bean(name = "test1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.test1")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
} @Bean(name = "test1SqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
return bean.getObject();
} @Bean(name = "test1TransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
} @Bean(name = "test1SqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
} }

最关键的地方就是这块了,一层一层注入,首先创建DataSource,然后创建SqlSessionFactory再创建事务,最后包装到SqlSessionTemplate中。其中需要指定分库的mapper文件地址,以及分库dao层代码

@MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")

这块的注解就是指明了扫描dao层,并且给dao层注入指定的SqlSessionTemplate。所有@Bean都需要按照命名指定正确。

dao层和xml层

dao层和xml需要按照库来分在不同的目录,比如:test1库dao层在com.neo.mapper.test1包下,test2库在com.neo.mapper.test1

public interface User1Mapper {

	List<UserEntity> getAll();

	UserEntity getOne(Long id);

	void insert(UserEntity user);

	void update(UserEntity user);

	void delete(Long id);

}

xml层

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.neo.mapper.test1.User1Mapper" >
<resultMap id="BaseResultMap" type="com.neo.entity.UserEntity" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="userName" property="userName" jdbcType="VARCHAR" />
<result column="passWord" property="passWord" jdbcType="VARCHAR" />
<result column="user_sex" property="userSex" javaType="com.neo.enums.UserSexEnum"/>
<result column="nick_name" property="nickName" jdbcType="VARCHAR" />
</resultMap> <sql id="Base_Column_List" >
id, userName, passWord, user_sex, nick_name
</sql> <select id="getAll" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM users
</select> <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM users
WHERE id = #{id}
</select> <insert id="insert" parameterType="com.neo.entity.UserEntity" >
INSERT INTO
users
(userName,passWord,user_sex)
VALUES
(#{userName}, #{passWord}, #{userSex})
</insert> <update id="update" parameterType="com.neo.entity.UserEntity" >
UPDATE
users
SET
<if test="userName != null">userName = #{userName},</if>
<if test="passWord != null">passWord = #{passWord},</if>
nick_name = #{nickName}
WHERE
id = #{id}
</update> <delete id="delete" parameterType="java.lang.Long" >
DELETE FROM
users
WHERE
id =#{id}
</delete> </mapper>

测试

测试可以使用SpringBootTest,也可以放到Controller中,这里只贴Controller层的使用

@RestController
public class UserController { @Autowired
private User1Mapper user1Mapper; @Autowired
private User2Mapper user2Mapper; @RequestMapping("/getUsers")
public List<UserEntity> getUsers() {
List<UserEntity> users=user1Mapper.getAll();
return users;
} @RequestMapping("/getUser")
public UserEntity getUser(Long id) {
UserEntity user=user2Mapper.getOne(id);
return user;
} @RequestMapping("/add")
public void save(UserEntity user) {
user2Mapper.insert(user);
} @RequestMapping(value="update")
public void update(UserEntity user) {
user2Mapper.update(user);
} @RequestMapping(value="/delete/{id}")
public void delete(@PathVariable("id") Long id) {
user1Mapper.delete(id);
} }

示例代码-github

示例代码-码云

springboot(七):springboot+mybatis多数据源最简解决方案的更多相关文章

  1. (转)Spring Boot(七):Mybatis 多数据源最简解决方案

    http://www.ityouknow.com/springboot/2016/11/25/spring-boot-multi-mybatis.html 说起多数据源,一般都来解决那些问题呢,主从模 ...

  2. Spring Boot(七):Mybatis 多数据源最简解决方案

    说起多数据源,一般都来解决那些问题呢,主从模式或者业务比较复杂需要连接不同的分库来支持业务.我们遇到的情况是后者,网上找了很多,大都是根据 Jpa 来做多数据源解决方案,要不就是老的 Spring 多 ...

  3. spring-boot (四) springboot+mybatis多数据源最简解决方案

    学习文章来自:http://www.ityouknow.com/spring-boot.html 配置文件 pom包就不贴了比较简单该依赖的就依赖,主要是数据库这边的配置: mybatis.confi ...

  4. spring boot(七):springboot+mybatis多数据源最简解决方案

    说起多数据源,一般都来解决那些问题呢,主从模式或者业务比较复杂需要连接不同的分库来支持业务.我们项目是后者的模式,网上找了很多,大都是根据jpa来做多数据源解决方案,要不就是老的spring多数据源解 ...

  5. SpringBoot ( 七 ) :springboot + mybatis 多数据源最简解决方案

    说起多数据源,一般都来解决那些问题呢,主从模式或者业务比较复杂需要连接不同的分库来支持业务.我们项目是后者的模式,网上找了很多,大都是根据jpa来做多数据源解决方案,要不就是老的spring多数据源解 ...

  6. springboot--springboot+mybatis多数据源最简解决方案

    说起多数据源,一般都来解决那些问题呢,主从模式或者业务比较复杂需要连接不同的分库来支持业务.我们项目是后者的模式,网上找了很多,大都是根据jpa来做多数据源解决方案,要不就是老的spring多数据源解 ...

  7. SpringBoot(七)-SpringBoot JPA-Hibernate

    步骤 1.在pom.xml添加mysql,spring-data-jpa依赖2.在application.properties文件中配置mysql连接配置文件3.在application.proper ...

  8. SpringBoot(七) SpringBoot中的缓存机制

    随着时间的积累,应用的使用用户不断增加,数据规模也越来越大,往往数据库查询操作会成为影响用户使用体验的瓶颈,此时使用缓存往往是解决这一问题非常好的手段之一.Spring 3开始提供了强大的基于注解的缓 ...

  9. springboot(七).springboot整合jedis实现redis缓存

    我们在使用springboot搭建微服务的时候,在很多时候还是需要redis的高速缓存来缓存一些数据,存储一些高频率访问的数据,如果直接使用redis的话又比较麻烦,在这里,我们使用jedis来实现r ...

随机推荐

  1. Jquery ajax 与 lazyload的混合使用(实现图片异步加载)

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  2. python基础之循环语句

    一.if条件语句: 语法: 1.if单分支(单重条件判断) if expression: expr_true_suite 注释:expession为真执行代码expr_true_suite if单分支 ...

  3. The eighth day

    time n(名词):时间:次,时代,时刻: vt(及物动词):为...安排时间:测定...的时间:调准(机械的速度): vi(不及物动词):合拍,和谐,打拍子 files (原型是fly) vi(不 ...

  4. bootstrapValidator 如何重新启用提交按钮

    bootstrapValidator 使用中,由于字段检查等原因,致使提交按钮失效.如何重新启用提交按钮呢? 下面一句代码可以实现启用提交按钮: $('#loginForm').bootstrapVa ...

  5. CocoStudio UIButton setPressedActionEnabled(true) 子控件不跟着缩放

    具体情况是这样的:美术给了我 一个按钮的背景图片  一个按钮的文字图片,用背景图片创建一个button,然后把文字图片添加进去(注意关闭文字图片的交互功能) 设置UIButton setPressed ...

  6. 在数据绑定控件(如:Repeater)中使用if判断

    方法: target="<%# DataBinder.Eval(Container.DataItem, "数据库字段").ToString() == "t ...

  7. Hadoop之—— WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform...

    [hadoop@hadoop000 hadoop]$ ldd --version ldd (GNU libc) 2.12 Copyright (C) Free Software Foundation, ...

  8. LeetCode Number of 1 Bits 计算1的个数

    题意: 提供一个无符号32位整型uint32_t变量n,返回其二进制形式的1的个数. 思路: 考察二进制的特性,设有k个1,则复杂度为O(k).考虑将当前的数n和n-1做按位与,就会将n的最后一个1去 ...

  9. linux命令 ——目录

    开始详细系统的学习linux常用命令,坚持每天一个命令,所以这个系列为每天一个linux命令.学习的主要参考资料为: 1.<鸟哥的linux私房菜> 2.http://codingstan ...

  10. 配置Maven镜像与本地缓存

    IntelliJ IDEA 安装后自带Maven,也可以使用自己安装的Maven. 配置阿里镜像与本地仓库文件夹 找到Maven的安装目录 打开settings.xml配置文件   修改mirrors ...