二.SpringBoot集成实例系列-xml型多数据源mybatis

来源:互联网 发布:淘宝怎么找同城店铺 编辑:程序博客网 时间:2024/06/08 04:43
文章列表
本系列将通过实例分别实现Springboot集成mybatis(mysql),mail,mongodb,cassandra,scheduler,redis,kafka,shiro,websocket。
具体文章系列如下:
一.SpringBoot集成实例系列-xml型单数据源mybatis
二.SpringBoot集成实例系列-xml型多数据源mybatis
三.SpringBoot集成实例系列-注解型单数据源mybatis
四.SpringBoot集成实例系列-注解型多数据源mybatis
五.SpringBoot集成实例系列-邮件email
六.SpringBoot集成实例系列-单数据源mongodb
七.SpringBoot集成实例系列-多数据源mongodb
八.SpringBoot集成实例系列-缓存redis
九.SpringBoot集成实例系列-数据库cassandra
十.SpringBoot集成实例系列-定时任务scheduler
十一.SpringBoot集成实例系列-消息队列kafka
十二.SpringBoot集成实例系列-消息推送websocket


上一篇博文我们实现了SpringBoot集成实例系列-xml型单数据源mybatis,该博文只是使用单数据源,而我们的项目中一般都使用多数据源(同源不同库或者不同源等),那如果出现这种情况我们在springboot中怎么实现呢?本文将通过实例实现springboot集成多数据源。

1.需求

输出库test中表user的记录和库test2中表user的记录总和
建表语句见博文或源码

2.技术要点

2.1 springboot集成mybatis配置


配置多个数据源如:
spring.datasource.test1...
spring.datasource.test2...
以此类推

2.2 多数据实现


1)@MapperScan(basePackages = "com.lm.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate")
配置需要扫描的mapper接口
2)@Bean(name = "test1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.test1")
@Primary
定义datasource,以及已application.properties配置文件数据源对应的名称
@Primary,当多个数据源时,需要定义一个主数据源,即优先考虑被注解的对象注入
3)bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"))
配置数据源对应的myabtis中mapper.xml路径

3.代码实现

3.1 项目结构


3.2 properties配置文件

mybatis.config-locations=classpath:mybatis/mybatis-config.xmlspring.datasource.test1.driverClassName = com.mysql.jdbc.Driverspring.datasource.test1.url = jdbc:mysql://192.168.32.128:3306/test?useUnicode=true&characterEncoding=utf-8spring.datasource.test1.username = rootspring.datasource.test1.password = rootspring.datasource.test2.driverClassName = com.mysql.jdbc.Driverspring.datasource.test2.url = jdbc:mysql://192.168.32.128:3306/test2?useUnicode=true&characterEncoding=utf-8spring.datasource.test2.username = rootspring.datasource.test2.password = root

3.3 datasource数据源实现

DataSource1Config文件
package com.lm.datasource;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.SqlSessionTemplate;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 org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource;/** * test1数据源 *  * @author liangming.deng * @date 2017年6月30日 * */@Configuration@MapperScan(basePackages = "com.lm.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate")public class DataSource1Config {@Bean(name = "test1DataSource")@ConfigurationProperties(prefix = "spring.datasource.test1")@Primarypublic DataSource testDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "test1SqlSessionFactory")@Primarypublic 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")@Primarypublic DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}@Bean(name = "test1SqlSessionTemplate")@Primarypublic SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate(sqlSessionFactory);}}
DataSource2Config文件
package com.lm.datasource;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.SqlSessionTemplate;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.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource;/** * test2数据源 *  * @author liangming.deng * @date 2017年6月30日 * */@Configuration@MapperScan(basePackages = "com.lm.mapper.test2", sqlSessionTemplateRef = "test2SqlSessionTemplate")public class DataSource2Config {@Bean(name = "test2DataSource")@ConfigurationProperties(prefix = "spring.datasource.test2")public DataSource testDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "test2SqlSessionFactory")public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource)throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test2/*.xml"));return bean.getObject();}@Bean(name = "test2TransactionManager")public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}@Bean(name = "test2SqlSessionTemplate")public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate(sqlSessionFactory);}}

3.4 User1Mapper和User2Mapper接口

User1Mapper接口
package com.lm.mapper.test1;import java.util.List;import com.lm.entity.UserEntity;/** * mybatis中mapper接口 * @author liangming.deng * @date   2017年6月21日 * */public interface User1Mapper {List<UserEntity> getAll();UserEntity getUserById(Long id);void insert(UserEntity user);void update(UserEntity user);void delete(Long id);}

User2Mapper接口
package com.lm.mapper.test2;import java.util.List;import com.lm.entity.UserEntity;/** * mybatis中mapper接口 * @author liangming.deng * @date   2017年6月21日 * */public interface User2Mapper {List<UserEntity> getAll();UserEntity getUserById(Long id);void insert(UserEntity user);void update(UserEntity user);void delete(Long id);}

3.5 mapper.xml文件

User1Mapper.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.lm.mapper.test1.User1Mapper"><resultMap id="BaseResultMap" type="com.lm.entity.UserEntity"><id column="id" property="id" jdbcType="BIGINT" /><result column="userName" property="userName" jdbcType="VARCHAR" /><result column="nickName" property="nickName" jdbcType="VARCHAR" /><result column="passWord" property="passWord" jdbcType="VARCHAR" /><result column="email" property="email" jdbcType="VARCHAR" /><result column="regTime" property="regTime" jdbcType="DATE" /><result column="sex" property="sexEnums" javaType="com.lm.enums.SexEnums" /></resultMap><sql id="Base_Column_List">id, userName, nickName,passWord, email,regTime,sex</sql><select id="getAll" resultMap="BaseResultMap">SELECT<include refid="Base_Column_List" />FROM user</select><select id="getUserById" parameterType="java.lang.Long" resultMap="BaseResultMap">SELECT<include refid="Base_Column_List" />FROM userWHERE id = #{id}</select><insert id="insert" parameterType="com.lm.entity.UserEntity">INSERT INTOuser(userName, nickName,passWord, email,regTime,sex)VALUES(#{userName},#{nickName}, #{passWord},#{email}, #{regTime},#{sexEnums})</insert><update id="update" parameterType="com.lm.entity.UserEntity">UPDATEuserSET<if test="userName != null">userName = #{userName},</if><if test="passWord != null">passWord = #{passWord}</if>WHEREid = #{id}</update><delete id="delete" parameterType="java.lang.Long">DELETE FROMuserWHEREid =#{id}</delete></mapper>
User2Mapper.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.lm.mapper.test2.User2Mapper"><resultMap id="BaseResultMap" type="com.lm.entity.UserEntity"><id column="id" property="id" jdbcType="BIGINT" /><result column="userName" property="userName" jdbcType="VARCHAR" /><result column="nickName" property="nickName" jdbcType="VARCHAR" /><result column="passWord" property="passWord" jdbcType="VARCHAR" /><result column="email" property="email" jdbcType="VARCHAR" /><result column="regTime" property="regTime" jdbcType="DATE" /><result column="sex" property="sexEnums" javaType="com.lm.enums.SexEnums" /></resultMap><sql id="Base_Column_List">id, userName, nickName,passWord, email,regTime,sex</sql><select id="getAll" resultMap="BaseResultMap">SELECT<include refid="Base_Column_List" />FROM user</select><select id="getUserById" parameterType="java.lang.Long" resultMap="BaseResultMap">SELECT<include refid="Base_Column_List" />FROM userWHERE id = #{id}</select><insert id="insert" parameterType="com.lm.entity.UserEntity">INSERT INTOuser(userName, nickName,passWord, email,regTime,sex)VALUES(#{userName},#{nickName}, #{passWord},#{email}, #{regTime},#{sexEnums})</insert><update id="update" parameterType="com.lm.entity.UserEntity">UPDATEuserSET<if test="userName != null">userName = #{userName},</if><if test="passWord != null">passWord = #{passWord}</if>WHEREid = #{id}</update><delete id="delete" parameterType="java.lang.Long">DELETE FROMuserWHEREid =#{id}</delete></mapper>

3.6 前端控制器controller

package com.lm.web;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.lm.entity.UserEntity;import com.lm.mapper.test1.User1Mapper;import com.lm.mapper.test2.User2Mapper;/** * 前端控制器 * @author liangming.deng * @date   2017年6月30日 * */@RestControllerpublic class UserController {    @Autowired    private User1Mapper user1Mapper;@Autowiredprivate User2Mapper user2Mapper;@RequestMapping("/getUsers")public List<UserEntity> getUsers() {List<UserEntity> users=user1Mapper.getAll();return users;}@RequestMapping("/getAllUserSize")public String getAllUserSize() {int test1UserSize = user1Mapper.getAll().size();int test2UserSize = user2Mapper.getAll().size();StringBuilder sBuilder = new StringBuilder();sBuilder.append("test1UserSize:").append(test1UserSize).append( " + ").append("test2UserSize:").append(test2UserSize).append(" = ").append(test1UserSize+test2UserSize);return sBuilder.toString();}@RequestMapping("/getUser")    public UserEntity getUser(Long id) {    UserEntity user=user2Mapper.getUserById(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);    }        }

3.7 运行效果


4. 代码地址

源码地址:
Github:https://github.com/a123demi/spring-boot-integration