Mybatis实现一对多和多对一的实现方式(各两种)

Mybatis实现一对多和多对一

  1. 项目结构
    在这里插入图片描述

  2. pom依赖

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <parent>
         <artifactId>spring-data</artifactId>
         <groupId>com.demo</groupId>
         <version>1.0-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>spring-boot-mybatis</artifactId>
     <properties>
         <maven.compiler.source>11</maven.compiler.source>
         <maven.compiler.target>11</maven.compiler.target>
     </properties>
    
     <dependencies>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
         </dependency>
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
         </dependency>
         <dependency>
             <groupId>org.mybatis.spring.boot</groupId>
             <artifactId>mybatis-spring-boot-starter</artifactId>
             <version>2.1.3</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
         </dependency>
         <dependency>
             <groupId>org.projectlombok</groupId>
             <artifactId>lombok</artifactId>
         </dependency>
       </dependencies>
    </project>
    
  3. yml配置文件

    server:
    port: 9100
    spring:
       datasource:
          username: gz
          password: gz
          url: jdbc:mysql://192.168.1.8:3306/mybatis?useUnicode=true&serverTimezone=UTC
          driver-class-name: com.mysql.cj.jdbc.Driver
    mybatis:
       configuration:
         map-underscore-to-camel-case: true
         log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
       mapper-locations: classpath:com/demo/mapper/*.xml
       #  type-aliases-package: com/demo/model  # 配置了这个xml配置文件中就可以使用别名了,默认类名首字母小写
    
  4. 启动类

    package com.demo;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
      * @version 1.0
      * @auther gz
      * @date 2021/11/1 - 21:58
      */
     @SpringBootApplication
     @MapperScan(basePackages = {"com.demo.mapper"})
     public class MybatisServerStarter {
     
          public static void main(String[] args){
              SpringApplication.run(MybatisServerStarter.class,args);
          }
     }
    
  5. model类

    package com.demo.model;
    
    import lombok.Data;
    
    /**
      * @version 1.0
      * @auther gz
      * @date 2021/11/1 - 23:31
      */
     @Data
     public class Student {
    
         private Integer id;
         
         private String name;
    
         private Integer tid;
    
         private Teacher teacher;
     }
    
    package com.demo.model;
    
    import lombok.Data;
    
    import java.util.List;
    
    /**
     * @version 1.0
     * @auther gz
     * @date 2021/11/1 - 23:31
     */
    @Data
    public class Teacher {
    
        private Integer id;
    
        private String name;
    
        private List<Student> studentList;
    
    }
    
  6. mapper类

    package com.demo.mapper;
    
    import com.demo.model.Student;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    import java.util.List;
    
    /**
     * @version 1.0
     * @auther gz
     * @date 2021/11/1 - 23:34
     */
    @Mapper
    public interface StudentMapper {
    
         List<Student> selectStudentByTid(@Param("tid")Integer tid);
    
         List<Student> selectStudentTeacherByTid(@Param("tid")Integer tid);
    
         List<Student> selectStudentTeacherByTid2(@Param("tid")Integer tid);
    
    }
    
    package com.demo.mapper;
    
    import com.demo.model.Teacher;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    import java.util.List;
    
      /**
       * @version 1.0
       * @auther gz
       * @date 2021/11/1 - 23:34
       */
    @Mapper
    public interface TeacherMapper {
           List<Teacher> selectTeacherByTid(@Param("tid")Integer tid);
    
           Teacher selectTeacherStudentByTid(@Param("tid") Integer tid);
    
           Teacher selectTeacherStudentByTid2(@Param("tid") Integer tid);
    }
    
  7. mapper映射文件

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
          PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
          "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.demo.mapper.StudentMapper">
    
        <!-- 多对一 实现方式一 -->
        <select id="selectStudentTeacherByTid" resultMap="studentTeacherMapper" parameterType="int">
            select s.id sid,s.name sname,t.id tid,t.name tname
            from tb_student s,tb_teacher t
            where s.tid = t.id and t.id = #{tid,jdbcType=INTEGER};
        </select>
        <resultMap id="studentTeacherMapper" type="com.demo.model.Student">
            <id property="id" column="sid"></id>
            <result property="name" column="sname"></result>
            <result property="tid" column="tid"></result>
            <association property="teacher" javaType="com.demo.model.Teacher">
               <id property="id" column="tid"></id>
               <result property="name" column="tname"></result>
            </association>
        </resultMap>
    
        <!-- 多对一  实现方式二  -->
        <select id="selectStudentTeacherByTid2" resultMap="studentTeacherMapper2" parameterType="int">
            select id ,name,tid
            from tb_student
            where tid = #{tid,jdbcType=INTEGER};
        </select>
        <resultMap id="studentTeacherMapper2" type="com.demo.model.Student">
              <!-- column 和 property一样的话可以省略 -->
             <result property="id" column="sid"></result>
             <result property="name" column="sname"></result>
             <result property="tid" column="tid"></result>
             <association property="teacher"
                          javaType="com.demo.model.Teacher"
                          column="tid"
                          select="com.demo.mapper.TeacherMapper.selectTeacherByTid">
             </association>
         </resultMap>
    
         <select id="selectStudentByTid" resultType="com.demo.model.Student">
              select id,name,tid from tb_student where tid = #{id};
         </select>
    </mapper>       
    
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     <mapper namespace="com.demo.mapper.TeacherMapper">
    
    
        <select id="selectTeacherByTid" resultType="com.demo.model.Teacher">
             select id,name from tb_teacher where id = #{tid};
        </select>
    
        <!-- 一对多实现方式一:-->
        <select id="selectTeacherStudentByTid" resultMap="teacherStudentMapper" parameterType="integer">
            select t.id tid, t.name tname , s.id sid, s.name sname
            from tb_teacher t,tb_student s
            where t.id = s.tid and t.id = #{tid,jdbcType=INTEGER};
        </select>
        <resultMap id="teacherStudentMapper" type="com.demo.model.Teacher">
            <id property="id" column="tid"></id>
            <result property="name" column="tname"></result>
            <collection property="studentList" ofType="com.demo.model.Student">
                <id property="id" column="sid"></id>
                <result property="name" column="sname"></result>
                <result property="tid" column="tid"></result>
            </collection>
        </resultMap>
    
    
        <!--  一对多实现方式二  -->
        <select id="selectTeacherStudentByTid2" resultMap="teacherStudentMapper2" parameterType="integer">
             select id , name
             from tb_teacher
             where id = #{tid,jdbcType=INTEGER};
        </select>
        <resultMap id="teacherStudentMapper2" type="com.demo.model.Teacher">
            <id property="id" column="id"></id>
            <result property="name" column="name"></result>
            <collection
                property="studentList"
                javaType="ArrayList"
                ofType="com.demo.model.Student"
                column="id"
                select="com.demo.mapper.StudentMapper.selectStudentByTid"
            >
            </collection>
    
        </resultMap>
    </mapper>
    
  8. 测试代码

    package com.demo;
    
    import com.demo.mapper.StudentMapper;
    import com.demo.mapper.TeacherMapper;
    import com.demo.model.Student;
    import com.demo.model.Teacher;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import javax.annotation.Resource;
    import java.util.List;
    
    /**
     * @version 1.0
     * @auther gz
     * @date 2021/11/1 - 23:52
     */
    @SpringBootTest
    @RunWith(SpringJUnit4ClassRunner.class)
    public class MyTest {
    
        @Resource
        private StudentMapper studentMapper;
    
        @Resource
        private TeacherMapper teacherMapper;
    
        /**
          * 测试多对一
          */
        @Test
        public void testMybatis(){
              List<Student> students1 = studentMapper.selectStudentTeacherByTid1(1);
              List<Student> students2 = studentMapper.selectStudentTeacherByTid2(1);
              System.out.println(students1);
              System.out.println(students2);
        }
    
        /**
         * 测试多对一
         */
        @Test
        public void testMybatis2(){
             Teacher teachers1 = teacherMapper.selectTeacherStudentByTid(1);
             Teacher teachers2 = teacherMapper.selectTeacherStudentByTid2(1);
             System.out.println(teachers1);
             System.out.println(teachers2);
        }
    }
    
  9. 数据库表
    tb_student
    在这里插入图片描述
    tb_teacher
    在这里插入图片描述

  10. 测试结果自己脑补吧

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值