回复
SpringBoot-Mybatis多数据源配置
qshy
发布于 2022-4-25 21:38
浏览
0收藏
作者 | springboot葵花宝典
来源 | 今日头条
之前我们介绍过Mybatis代码生成有两种方式:
- Mybatis Genenrator Mybatis代码生成
- Mybtais Plus MyBatisPlus代码生成
在之前介绍JdbcTemplate和Spring-Boot-Data操作数据库的时候也分别介绍了
- JdbcTemplate多数据源配置
- Spring-Data-JPA多数据源配置本次章节的实体类的sql也在该章节
今天我们介绍Mybatis使用时候的多数源配置如何实现。
该测试项目的整体框架如下:
多数据源配置
在项目的application.yml中设置要链接的数据库,配置如下:
server:
port: 8899
spring:
datasource:
student:
jdbc-url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
teacher:
jdbc-url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
注:
在spring1.x和spring2.x中数据库配置链接关键字有区别:
- 在1.x中配置的是spring.datasource.XXX.url
- 在2.x中配置的是spring.datasource.XXX.jdbc-url
数据源的配置
主数据源的配置
在这次配置中我们将mybatis数据库作为主数据库,里面包含了student表,其主要配置如下:
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.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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 javax.sql.DataSource;
@Configuration
//数据源student库接口存放目录
@MapperScan(basePackages = "com.learn.springboot.entity.student",
sqlSessionTemplateRef = "sqlSessionTemplateStudent")
public class MybatisStudentConfig {
/**
* 主数据源默认使用Student
*
* @return
*/
@Primary
@Bean
@ConfigurationProperties(prefix = "spring.datasource.student")
public DataSource studentDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory sqlSessionFactoryStudent() throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(studentDataSource());
//设置XML文件存放位置.注意这里student目录
bean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/student/*.xml"));
return bean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplateStudent() throws Exception {
return new SqlSessionTemplate(sqlSessionFactoryStudent());
}
}
注:
- 主数据源要是有**@Primary**进行表示
- bean.setMapperLocations(new PathMatchingResourcePatternResolver()
- .getResources("classpath:mapper/teacher/*.xml"));用于配置xml的位置
- 配置类上使用@MapperScan注解来是用来扫描实体类和Mapper包路径
非主数据源的配置
在这次配置中我们将mysql数据库作为非主数据库,里面包含了teacher表,其主要配置如下:
@Configuration
//数据源teacher库接口存放目录
@MapperScan(basePackages = "com.learn.springboot.entity.teacher",
sqlSessionTemplateRef = "sqlSessionTemplateTeacher")
public class MybatisTeacherConfig {
/**
* 主数据源默认使用Student
*
* @return
*/
@Bean
@ConfigurationProperties(prefix = "spring.datasource.teacher")
public DataSource teacherDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory sqlSessionFactoryTeacher() throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(teacherDataSource());
//设置XML文件存放位置,注意这里teacher目录
bean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/teacher/*.xml"));
return bean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplateTeacher() throws Exception {
return new SqlSessionTemplate(sqlSessionFactoryTeacher());
}
}
实体类的创建
本次章节的实体类分别有student和teacher两个实体类,代码如下
@Data
public class Student {
private Long id;
private String name;
private String sex;
private int age;
private String email;
private String mobile;
private int isEnabled;
private Date createDate;
private Date updateDate;
}
@Data
public class Teacher {
private Long id;
private String name;
private String sex;
private String course;
private int age;
private String email;
private String mobile;
private int isEnabled;
private Date createDate;
private Date updateDate;
}
Mapper的实现
student的mapper接口的xml配置实现如下
- studentmapper接口
public interface StudentMapper {
Student findById(@Param("id") Long id);
void updateStudent(Student student);
int insertByObject(Student student);
}
- studentmapper的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.learn.springboot.entity.student.StudentMapper">
<select id="findById" resultType="com.learn.springboot.entity.student.Student">
SELECT * FROM STUDENT WHERE ID = #{id}
</select>
<insert id="insertByObject">
INSERT INTO STUDENT(NAME, SEX,AGE,EMAIL,MOBILE) VALUES(#{name}, #{sex}, #{age}, #{email}, #{mobile})
</insert>
<update id="updateStudent" parameterType="com.learn.springboot.entity.student.Student">
UPDATE STUDENT SET NAME=#{name},SEX=#{sex},AGE=#{age},EMAIL=#{email},MOBILE=#{mobile} WHERE id=#{id}
</update>
</mapper>
teacher的mapper接口的xml配置实现如下
- teachermapper的接口如下:
public interface TeacherService {
Teacher updateTeacher(Teacher teacher);
int insertByObject(Teacher teacher);
Teacher findById(Long id);
}
- teachermapper的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.learn.springboot.entity.teacher.TeacherMapper">
<select id="findById" resultType="com.learn.springboot.entity.teacher.Teacher">
SELECT * FROM TEACHER WHERE ID = #{id}
</select>
<insert id="insertByObject">
INSERT INTO TEACHER(NAME, SEX,AGE,EMAIL,MOBILE) VALUES(#{name}, #{sex}, #{age}, #{email}, #{mobile})
</insert>
<update id="updateTeacher" parameterType="com.learn.springboot.entity.teacher.Teacher">
UPDATE TEACHER SET NAME=#{name},SEX=#{sex},AGE=#{age},EMAIL=#{email},MOBILE=#{mobile} WHERE id=#{id}
</update>
</mapper>
Service层的实现
student的Service层实现
student的service包含studentservice接口和其实现StudentServiceimpl代码实现如下:
- StudentService接口的实现
public interface StudentService {
Student updateStudent(Student student);
int insertByObject(Student student);
Student findById(Long id);
}
- StudentServiceImpl的实现代码:
@Service
public class StudentServiceImpl implements StudentService {
private StudentMapper studentMapper;
@Override
public int insertByObject(Student student){
return studentMapper.insertByObject(student);
}
@Override
public Student updateStudent(Student student){
studentMapper.updateStudent(student);
return student;
}
@Override
public Student findById(Long id) {
return studentMapper.findById(id);
}
}
teacher的Service实现
student的service包含studentservice接口和其实现StudentServiceimpl代码实现如下:
- StudentService接口的实现
public interface TeacherService {
Teacher updateTeacher(Teacher teacher);
int insertByObject(Teacher teacher);
Teacher findById(Long id);
}
- TeacherServiceImpl的实现代码:
@AllArgsConstructor
@Service
public class TeacherServiceImpl implements TeacherService {
private TeacherMapper teacherMapper;
@Override
public int insertByObject(Teacher teacher){
return teacherMapper.insertByObject(teacher);
}
@Override
public Teacher updateTeacher(Teacher teacher){
teacherMapper.updateTeacher(teacher);
return teacher;
}
@Override
public Teacher findById(Long id) {
return teacherMapper.findById(id);
}
}
控制层的实现
- Student的控制层代码实现如下
@Slf4j
@RequestMapping("/student")
@RestController
@AllArgsConstructor
public class StudentController {
/**
* studentService注入StudentController
*/
private StudentService studentService;
@PostMapping("insert")
public int insertByObject(@RequestBody Student student){
return studentService.insertByObject(student);
}
@PostMapping("update")
public Student updateStudent(@RequestBody Student student) {
return studentService.updateStudent(student);
}
@GetMapping("/select/{id}")
public Student findByName(@PathVariable("id") Long id) {
return studentService.findById(id);
}
}
- Teacher的控制层代码实现如下
@Slf4j
@RequestMapping("/teacher")
@RestController
@AllArgsConstructor
public class TeacherController {
/**
* teacherService注入TeacherController
*/
private TeacherService teacherService;
@PostMapping("insert")
public int insertByObject(@RequestBody Teacher teacher){
return teacherService.insertByObject(teacher);
}
@PostMapping("update")
public Teacher updateStudent(@RequestBody Teacher teacher) {
return teacherService.updateTeacher(teacher);
}
@GetMapping("/select/{id}")
public Teacher findByName(@PathVariable("id") Long id) {
return teacherService.findById(id);
}
}
测试
使用postman分别测试
- http://localhost:8899/student/select/11 Get方法
- http://localhost:8899/teacher/update Post方法
- http://localhost:8899/teacher/select/11 Get方法
分别测试了student和teacher的方法以及Get和Post方法。
赞
收藏
回复
相关推荐