Spring boot(七):Spring boot+ mybatis 多数据源最简解决方案

多数据源一般解决哪些问题?主从模式或者业务比较复杂需要连接不同的分库来支持业务。

直接上代码。

配置文件

pom包依赖,该依赖的依赖。主要是数据库这边的配置:

mybatis.config-locations=classpath:mybatis/mybatis-config.xmlspring.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 = rootspring.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")@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);}}

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

@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.test2下

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 usersWHERE 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 FROMusers WHERE id =#{id}</delete></mapper>

测试

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

@RestController
public class UserController {@Autowiredprivate User1Mapper user1Mapper;@Autowiredprivate 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);}
}

项目地址(码云)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/330964.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java:关于main方法的10道面试题

转载自 Java&#xff1a;关于main方法的10道面试题 1.main方法是做什么用的&#xff1f; 2.不用main方法如何运行一个类&#xff1f; 3.main方法如何传递参数&#xff1f;传递参数的类型是什么&#xff1f;能不能改变该参数类型&#xff1f; 4.main方法为什么是静态的&#xff…

ReviewForJob——深度优先搜索的应用

【0】README 1&#xff09;本文旨在 介绍 ReviewForJob——深度优先搜索的应用 及其 源码实现 &#xff1b; 2&#xff09;搜索树的技术分为广度优先搜索 和 深度优先搜索&#xff1a;而广度优先搜索&#xff0c;我们前面利用 广度优先搜索计算无权最短路径已经做过分析了&am…

Spring boot(八):RabbitMQ详解

RabbitMQ介绍 RabbitMQ既一个消息队列&#xff0c;主要用来实现应用程序的异步和解耦&#xff0c;同时也能起到消息缓冲&#xff0c;消息分发的作用。 消息中间件在互联网公司的使用中越来越多。消息中间件最主要的作用是解耦&#xff0c;中间件最标准的用法师生产者生产消息传…

关于Jvm知识看这一篇就够了

转载自 关于Jvm知识看这一篇就够了2016年左右的时候读了周志明《深入理解Java虚拟机&#xff1a;JVM高级特性与最佳实践》&#xff0c;读完之后受益匪浅&#xff0c;让我对Java虚拟机有了一个完整的认识&#xff0c;这是Jvm书籍中最好的读物之一。后来结合实际工作中遇到的问题…

ReviewForJob——算法设计技巧(贪婪算法+分治算法+动态规划)

【0】README 1&#xff09;本文旨在介绍算法设计技巧包括 贪婪算法、分治算法、动态规划 以及相关的荔枝等&#xff1b; 【1】贪婪算法 1&#xff09;intro&#xff1a; 贪婪算法是分阶段进行的&#xff0c;在每个阶段&#xff0c;可以认为所做的决定是最好的&#xff0c;而…

Spring boot(九):定时任务

在我们的项目开发过程中&#xff0c;进场需要定时任务来帮助我们做一些内容&#xff0c;springboot默认已经帮我们实行了&#xff0c;只要天剑相应的注解就可以实现。 1、pom包配置 pom包里面只需要引入springboot starter包即可 <dependencies><dependency><…

jvm系列(一):java类的加载机制

转载自 jvm系列(一):java类的加载机制1、什么是类的加载 类的加载指的是将类的.class文件中的二进制数据读入到内存中&#xff0c;将其放在运行时数据区的方法区内&#xff0c;然后在堆区创建一个 java.lang.Class对象&#xff0c;用来封装类在方法区内的数据结构。类的加载的最…

Springboot(十):邮件服务

发送邮件应该是网站的必备功能之一&#xff0c;什么注册验证&#xff0c;忘记密码或者是给用户发送营销信息。最早期的时候我们会使用javaMail相关api来写邮件相关代码&#xff0c;后来spring退出了javaMailSender 更加简化了邮件发送的过程&#xff0c;在之后springboot 对此进…

How to install plugin for Eclipse from .zip

these contents are reshiped from 如何在eclipse中安装.zip插件 1.make sure your .zip file is an valid Eclipse Plugin Note: that means: your .zip file contains folders features and plugins, like this:for new version Eclipse Plugin, it may also include anothe…

jvm系列(二):JVM内存结构

转载自 jvm系列(二):JVM内存结构所有的Java开发人员可能会遇到这样的困惑&#xff1f;我该为堆内存设置多大空间呢&#xff1f;OutOfMemoryError的异常到底涉及到运行时数据的哪块区域&#xff1f;该怎么解决呢&#xff1f;其实如果你经常解决服务器性能问题&#xff0c;那么这…

jvm系列(三):GC算法 垃圾收集器

转载自 jvm系列(三):GC算法 垃圾收集器 概述 垃圾收集 Garbage Collection 通常被称为“GC”&#xff0c;它诞生于1960年 MIT 的 Lisp 语言&#xff0c;经过半个多世纪&#xff0c;目前已经十分成熟了。 jvm 中&#xff0c;程序计数器、虚拟机栈、本地方法栈都是随线程而生随线…

Spring boot(十二):Spring boot 如何测试、打包、部署

博文引用&#xff1a;springboot(十二)&#xff1a;springboot如何测试打包部署 开发阶段 单元测试 Spring boot对单元测试的支持已经很完善了。 1 在pom包中添加Spring-boot-starter-test包引用 <dependency><groupId>org.springframework.boot</groupId&g…

Java虚拟机详解----常用JVM配置参数

【声明】 欢迎转载&#xff0c;但请保留文章原始出处→_→ 生命壹号&#xff1a;http://www.cnblogs.com/smyhvae/ 文章来源&#xff1a;http://www.cnblogs.com/smyhvae/p/4736162.html 联系方式&#xff1a;smyhvae163.com 本文主要内容&#xff1a; Trace跟踪参数堆的…

jvm系列(四):jvm调优-命令篇

转载自 jvm系列(四):jvm调优-命令篇 运用jvm自带的命令可以方便的在生产监控和打印堆栈的日志信息帮忙我们来定位问题&#xff01;虽然jvm调优成熟的工具已经有很多&#xff1a;jconsole、大名鼎鼎的VisualVM&#xff0c;IBM的Memory Analyzer等等&#xff0c;但是在生产环境出…

Sprng boot(十三):Spring boot 小技巧

初始化数据 使用jpa 在使用Spring boot jpa的情况下设置 spring.jpa.hibernate.ddl-auto 的属性为 create 或 create-drop &#xff0c;Spring boot启动时默认会扫描classpath下面&#xff08;项目一般是resources目录&#xff09;是否有import.sql&#xff0c;如果有机会执行…

滴滴2017在线笔试有感

呵呵 刚才参加完了 滴滴2017的在线笔试。 又一次被虐。。班上很多人都在耍算法&#xff0c;这样算法 那样算法。其实今天看他的 题目 也就是 数据结构的基础知识&#xff0c; 没有多高深的算法。。当然这是一个小生的 匹夫之言&#xff1b; 编程第一题&#xff1a; 求最大子序列…

Mybatis3 XML属性配置

对象工厂&#xff08;ObjectFactory&#xff09; MyBatis 每次创建结果对象的新实例时&#xff0c;它都会使用一个对象工厂&#xff08;ObjectFactory&#xff09;实例来完成。默认的对象工厂需要做的仅仅是实例化目标类。如果想覆盖对象工厂的默认行为&#xff0c;则可以通过…

Eclipse反编译工具Jad及插件JadClipse配置

转自&#xff1a;http://www.blogjava.net/landon/archive/2010/07/16/326294.html Jad是一个Java的一个反编译工具&#xff0c;是用命令行执行&#xff0c;和通常JDK自带的java&#xff0c;javac命令是一样的。不过因为是控制台运行&#xff0c;所以用起来不太方便。不过幸好有…

jvm系列(五):Java GC 分析

转载自 jvm系列(五):Java GC 分析Java GC就是JVM记录仪&#xff0c;书画了JVM各个分区的表演。 什么是 Java GC Java GC&#xff08;Garbage Collection&#xff0c;垃圾收集&#xff0c;垃圾回收&#xff09;机制&#xff0c;是Java与C/C的主要区别之一&#xff0c;作为Java开…

Mybatis3 (2)xml映射文件

SQL 映射文件有很少的几个顶级元素&#xff08;按照它们应该被定义的顺序&#xff09;&#xff1a; cache – 给定命名空间的缓存配置。cache-ref – 其他命名空间缓存配置的引用。resultMap – 是最复杂也是最强大的元素&#xff0c;用来描述如何从数据库结果集中来加载对象。…