一个简单的例子学会mybatis-generator+tk.mybatis插件 实现父子表关系查询

项目环境:

开发环境:IntelliJ IDEA 2019.3.1 ,JDK1.8 ,MySQL: 5.6.47
采用远程数据库连接:使用ailiyun ESC CentOS 7.0

项目技术:

学会使用mybatis-generator自动部署代码
学会使用tk.mybatis插件进行数据库的操作
学会实现父子表管子查询

项目资源连接:示例源代码

项目说明

 本项目采用mybatis-generator的自动生成插件和Tk插件结合,实现对父子表的联合查询,使返回结果包括父表信息和它的子表每个子数据信息。
一个简单的例子学会mybatis-generator+tk.mybatis插件 实现父子表关系查询_第1张图片

项目准备

创建数据库schooldb

 使用Navicat创建数据库schooldb,并运行下面的sql文件

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for tbl_student
-- ----------------------------
DROP TABLE IF EXISTS `tbl_student`;
CREATE TABLE `tbl_student`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `teacher_id` bigint(20) NULL DEFAULT NULL,
  `name` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '学生姓名',
  `age` int(11) NULL DEFAULT NULL COMMENT '年龄',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Compact;

-- ----------------------------
-- Records of tbl_student
-- ----------------------------
INSERT INTO `tbl_student` VALUES (1, 1, '小明', 15);
INSERT INTO `tbl_student` VALUES (2, 1, '小李', 15);
INSERT INTO `tbl_student` VALUES (3, 1, '小红', 14);
INSERT INTO `tbl_student` VALUES (4, 2, '小李', 14);
INSERT INTO `tbl_student` VALUES (5, 2, '王二', 15);
INSERT INTO `tbl_student` VALUES (6, 2, '张三', 13);

-- ----------------------------
-- Table structure for tbl_teacher
-- ----------------------------
DROP TABLE IF EXISTS `tbl_teacher`;
CREATE TABLE `tbl_teacher`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '老师姓名',
  `age` int(11) NULL DEFAULT NULL COMMENT '老师年龄',
  `phone` int(11) NULL DEFAULT NULL COMMENT '手机号',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Compact;
-- ----------------------------
-- Records of tbl_teacher
-- ----------------------------
INSERT INTO `tbl_teacher` VALUES (1, '王老师', 45, 1596369856);
INSERT INTO `tbl_teacher` VALUES (2, '李老师', 32, 1358948956);

SET FOREIGN_KEY_CHECKS = 1;

项目结构

一个简单的例子学会mybatis-generator+tk.mybatis插件 实现父子表关系查询_第2张图片

一、依赖与配置

依赖

一个简单的例子学会mybatis-generator+tk.mybatis插件 实现父子表关系查询_第3张图片
pom.xml

<dependencies>
        <dependency>
            <groupId>tk.mybatisgroupId>
            <artifactId>mapper-spring-boot-starterartifactId>
            <version>2.0.4version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.1version>
        dependency>

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.10version>
        dependency>


        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
            
            <version>5.1.6version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
            <plugin>
                <groupId>org.mybatis.generatorgroupId>
                <artifactId>mybatis-generator-maven-pluginartifactId>
                <version>1.3.7version>
                <dependencies>
                    <dependency>
                        <groupId>mysqlgroupId>
                        <artifactId>mysql-connector-javaartifactId>
                        <scope>runtimescope>
                        
                        <version>5.1.6version>
                    dependency>
                    
                    <dependency>
                        <groupId>tk.mybatisgroupId>
                        <artifactId>mapperartifactId>
                        <version>4.1.5version>
                    dependency>
                dependencies>
                <configuration>
                    
                    <configurationFile>${basedir}/src/main/resources/mybatis-generator.xmlconfigurationFile>
                    <overwrite>trueoverwrite>
                    <verbose>trueverbose>
                configuration>
            plugin>
        plugins>
    build>

配置application.properties

#远程数据库连接
spring.datasource.url=jdbc:mysql://121.40.83.80:3306/schooldb?characterEncoding=UTF-8&useSSL=false
#数据库用户名
spring.datasource.username=alvin
#数据库密码
spring.datasource.password=123456
#数据源类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

mybatis.mapper-locations=classpath:/mapper/*.xml

配置Tk

 在utils包下 创建TkMapper.java类

/**
 * 继承
 * @param 
 */
public interface TkMapper<T> extends Mapper<T>, MySqlMapper<T> {
    //特别注意,该接口不能被扫描到,否则会出错
}

配置mybatis-generator.xml



<generatorConfiguration>
    <properties resource="application.properties"/>
    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="com.alvin.mybatis.utils.TkMapper"/>
            <property name="caseSensitive" value="true"/>
            <property name="forceAnnotation" value="true"/>
            <property name="beginningDelimiter" value="`"/>
            <property name="endingDelimiter" value="`"/>
        plugin>

        <commentGenerator>
            
            
            <property name="suppressDate" value="true" />
            
            <property name="suppressAllComments" value="false" />
        commentGenerator>
        
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://121.40.83.80:3306/schooldb"
                        userId="alvin"
                        password="123456">
        jdbcConnection>
        <javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
            
            <property name="forceBigDecimals" value="false"/>
        javaTypeResolver>


        
        <javaModelGenerator targetPackage="com.alvin.mybatis.model" targetProject="src/main/java">
            
            <property name="enableSubPackages" value="true"/>
            
            <property name="constructorBased" value="true"/>
            
            <property name="trimStrings" value="true"/>
            
            <property name="immutable" value="false"/>
        javaModelGenerator>

        
        <sqlMapGenerator targetPackage="mybatis" targetProject="src/main/resources">
            
            <property name="enableSubPackages" value="true"/>
        sqlMapGenerator>


        
        <javaClientGenerator targetPackage="com.alvin.mybatis.mapper" type="XMLMAPPER" targetProject="src/main/java">
            
            <property name="enableSubPackages" value="true"/>
        javaClientGenerator>

        
        <table tableName="tbl_student" domainObjectName="Student" enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
            <generatedKey column="id" sqlStatement="JDBC" identity="true"/>
        table>
        <table tableName="tbl_teacher" domainObjectName="Teacher" enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
            <generatedKey column="id" sqlStatement="JDBC" identity="true"/>
        table>
        <table tableName="tbl_teacher_student" domainObjectName="TeacherStudent" enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
            <generatedKey column="id" sqlStatement="JDBC" identity="true"/>
        table>
    context>
generatorConfiguration>

配置启动类

 这里需要在启动类加入一个注解@MapperScan(basePackages = "com.alvin.mybatis.mapper"),注意它的引包是import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
//com.alvin.mybatis.mapper是我们扫描.mapper的地址
@MapperScan(basePackages = "com.alvin.mybatis.mapper")
public class MybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}

配置data sources

一个简单的例子学会mybatis-generator+tk.mybatis插件 实现父子表关系查询_第4张图片
一个简单的例子学会mybatis-generator+tk.mybatis插件 实现父子表关系查询_第5张图片
一个简单的例子学会mybatis-generator+tk.mybatis插件 实现父子表关系查询_第6张图片

二、自动生成

一个简单的例子学会mybatis-generator+tk.mybatis插件 实现父子表关系查询_第7张图片
一个简单的例子学会mybatis-generator+tk.mybatis插件 实现父子表关系查询_第8张图片
自动生成结果如下
一个简单的例子学会mybatis-generator+tk.mybatis插件 实现父子表关系查询_第9张图片

三、实现父子表查询

数据层

  • StudentDto.java
public class StudentDto {
    private Long id;
    private String name;
    private Integer age;
    private Long teacherId;
    //省略setter/getter方法
}
  • TeacherDto.java
public class TeacherDto {
    private Long id;
    private String name;
    private Integer age;
    private Integer phone;
    private List<StudentDto> dtoList;
    //省略setter/getter方法
}

控制层

  • TestController.java
@Controller
public class TestController {
    @Autowired
    TestService testService;
    
    @ResponseBody
    @GetMapping("/test")
    public List<TeacherDto> search(
            @RequestParam Long id
    ){
        return testService.search(id);
    }
}

业务逻辑层

  • TestService.java
@Service
public class TestService {
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    TeacherMapper teacherMapper;

    public List<TeacherDto> search(Long id){

        List<TeacherDto>  repList = new ArrayList<>();
        TeacherDto teacherDto = new TeacherDto();
        //查询该老师的所有信息
        Teacher teacher = teacherMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(teacher,teacherDto);
        repList.add(teacherDto);
        //查询该老师的所有学生
        Example example = new Example(Student.class);
        example.createCriteria().andEqualTo("teacherId",id);
        List<Student> students = studentMapper.selectByExample(example);
        //查询每个学生的个人信息
        List<StudentDto> studentDtoList = new ArrayList<>();
        for(Student student : students){
            StudentDto studentDto = new StudentDto();
            BeanUtils.copyProperties(student,studentDto);

            studentDtoList.add(studentDto);
            teacherDto.setDtoList(studentDtoList);
        }
        return repList;
    }
}

也可以根据java8的特性使用stream代替for迭代

@Service
public class TestService {
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    TeacherMapper teacherMapper;

    public List<TeacherDto> search(Long id){

        List<TeacherDto>  repList = new ArrayList<>();
        TeacherDto teacherDto = new TeacherDto();
        //查询该老师的所有信息
        Teacher teacher = teacherMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(teacher,teacherDto);
        repList.add(teacherDto);
        //查询该老师的所有学生
        Example example = new Example(Student.class);
        example.createCriteria().andEqualTo("teacherId",id);
        List<Student> students = studentMapper.selectByExample(example);
        //查询每个学生的个人信息
        List<StudentDto> list = students.stream().map(student -> {
            StudentDto studentDto = new StudentDto();
            BeanUtils.copyProperties(student, studentDto);
            return studentDto;
        }).collect(Collectors.toList());
        teacherDto.setDtoList(list);
        return repList;
}

四、Postman调用

一个简单的例子学会mybatis-generator+tk.mybatis插件 实现父子表关系查询_第10张图片

你可能感兴趣的:(MySQL,Mybatis,#,SpringBoot持久层技术)