SpringBoot-21-Mybatis multi data source configuration

Posted by Ree on Mon, 07 Mar 2022 04:53:58 +0100

SpringBoot-21-Mybatis multiple data sources

As we mentioned earlier, there are two ways to generate Mybatis Code:

The JdbcTemplate and spring boot data operation databases were also introduced earlier

Today, we will introduce how to implement most source configurations when Mybatis is used.

The overall framework of the test project is as follows:

Multi data source configuration

In the application of the project Set the database to be linked in YML. The configuration is as follows:

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 support can be omitted
    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


Note:

  • In spring 1 X and spring2 There are differences in database configuration link keywords in X:

  • In 1 X is configured with spring datasource. XXX. url

  • In 2 X is configured with spring datasource. XXX. jdbc-url

Configuration of data source

Configuration of master data source

In this configuration, we take the mybatis database as the main database, which contains the student table. Its main configuration is as follows:

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
//Data source student library interface storage directory
@MapperScan(basePackages = "com.learn.springboot.entity.student",
        sqlSessionTemplateRef = "sqlSessionTemplateStudent")
public class MybatisStudentConfig {

    /**
     * The master data source uses Student by default
     *
     * @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());
        //Set the storage location of XML files Note the student directory here
        bean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/student/*.xml")); 
        return bean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplateStudent() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryStudent());
    }

}

Note:

  • The Primary data source is represented by * * @ Primary * *

  • bean.setMapperLocations(new PathMatchingResourcePatternResolver()
            .getResources("classpath:mapper/teacher/*.xml"));For configuration xml Location of
    
    
  • The @ MapperScan annotation on the configuration class is used to scan the entity class and Mapper package path

Configuration of non primary data sources

In this configuration, we take mysql database as a non primary database, which contains the teacher table. Its main configuration is as follows:

@Configuration
//Storage directory of data source teacher library interface
@MapperScan(basePackages = "com.learn.springboot.entity.teacher",
        sqlSessionTemplateRef = "sqlSessionTemplateTeacher")
public class MybatisTeacherConfig {
    /**
     * The master data source uses Student by default
     *
     * @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());
        //Set the storage location of XML files. Note the teacher directory here
        bean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/teacher/*.xml"));
        return bean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplateTeacher() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryTeacher());
    }

}

Creation of entity class

The entity classes in this chapter include student and teacher, and the codes are as follows

@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;

}


Implementation of Mapper

The xml configuration of the mapper interface of student is implemented as follows

  • studentmapper interface
public interface StudentMapper {
    Student findById(@Param("id") Long id);
    void updateStudent(Student student);
    int insertByObject(Student student);
}


  • The xml configuration of studentmapper is as follows
<?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>

The xml configuration of the mapper interface of teacher is implemented as follows

  • The interface of teachermapper is as follows:
public interface TeacherService {

    Teacher updateTeacher(Teacher teacher);
    int insertByObject(Teacher teacher);
    Teacher findById(Long id);
}


  • The xml configuration of the teacher mapper is as follows
<?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>

Implementation of Service layer

Implementation of student's Service layer

The student's service includes the studentservice interface and its implementation. The StudentServiceimpl code is implemented as follows:

  • Implementation of StudentService interface
public interface StudentService {
    Student updateStudent(Student student);
    int insertByObject(Student student);
    Student findById(Long id);

}


  • Implementation code of 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);
    }
}


Implementation of teacher Service

The student's service includes the studentservice interface and its implementation. The StudentServiceimpl code is implemented as follows:

  • Implementation of StudentService interface
public interface TeacherService {

    Teacher updateTeacher(Teacher teacher);
    int insertByObject(Teacher teacher);
    Teacher findById(Long id);
}



  • Implementation code of 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);
    }
}



Implementation of control layer

  • The control layer code of Student is implemented as follows
@Slf4j
@RequestMapping("/student")
@RestController
@AllArgsConstructor
public class StudentController {

    /**
     * studentService Inject 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);
    }
}


  • The control layer code of Teacher is implemented as follows
@Slf4j
@RequestMapping("/teacher")
@RestController
@AllArgsConstructor
public class TeacherController {

    /**
     * teacherService Inject 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);
    }
}


test

Use postman to test separately

  • http://localhost:8899/student/select/11 Get method

  • http://localhost:8899/teacher/update Post method

  • http://localhost:8899/teacher/select/11 Get method

The methods of student and teacher, Get and Post are tested respectively.

If you think this article is good, welcome to pay attention and support. Your attention is the driving force of my persistence!

springboot official account of sunflower collection

Original is not easy, reprint please indicate the source, thank you for your support! If this article is useful to you, welcome to forward and share!

Topics: Java MySQL Spring Spring Boot Back-end