文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Mybatis结果集映射一对多简单入门教程

2024-04-02 19:55

关注

Mybatis 一对多 简单入门 易懂

搭建数据库环境

student 表


DROP TABLE IF EXISTS `student_2`;
CREATE TABLE `student_2`  (
  `id` int(10) NOT NULL,
  `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `tid` int(10) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `fktid`(`tid`) USING BTREE,
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

INSERT INTO `student_2` VALUES (1, '小明', 1);
INSERT INTO `student_2` VALUES (2, '邱ss', 2);
INSERT INTO `student_2` VALUES (3, '邱大哥', 3);
INSERT INTO `student_2` VALUES (4, '杨大哥', 1);
INSERT INTO `student_2` VALUES (5, '杨ss', 2);

teacher


DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher`  (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of teacher
-- ----------------------------
INSERT INTO `teacher` VALUES (1, '小王老师');
INSERT INTO `teacher` VALUES (2, '小李老师');
INSERT INTO `teacher` VALUES (3, '小黑老师');

idea 搭建maven 项目 (mybatis-demo)

项目结构

在这里插入图片描述

导入依赖


<dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

mysql 配置文件


jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm-study?useSSL=false
jdbc.username=root
jdbc.password=123456

创建pojo 类

学生



public class Student {
    
    private Integer id;
    
    private String name;
    
    private Integer tid;
}

老师



public class Teacher {
    
    private Integer id;
    
    private String name;

    
    private List<Student> students;
}

写一个mybatis 的工具类



public class MybatisUtil {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource="mybatis-config.xml";
            InputStream inputStream= Resources.getResourceAsStream(resource);
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSession(){
        return sqlSessionFactory.openSession(true);
    }
}

写一个TeacherMapper


import com.crush.pojo.Teacher;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface TeacherMapper {

    // 获取老师
    List<Teacher> getTeacher();

    //获取指定老师下的所有学生及老师的信息
    Teacher getTeacher2(@Param("tid") Integer id);


    //获取指定老师下的所有学生及老师的信息
    Teacher getTeacher3(@Param("tid") Integer 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.crush.dao.TeacherMapper">


    <select id="getTeacher" resultType="Teacher">
        select * from teacher
    </select>

    <select id="getTeacher2" resultMap="TeacherStudent">
        select s.id sid,s.name sname,t.name tname,
           t.id tid from student_2 s,teacher t where s.tid=t.id and t.id=#{tid}
    </select>

    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--
            复杂的属性,我们需要单独处理 对象 association  集合collection
               javaType ="" 是指属性的类型
               集合中的泛型的信息 我们使用ofType 获取
        -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
         </collection>
    </resultMap>

    <!--========================= 结果集映射=============================-->
    <select id="getTeacher3" resultMap="TeacherStudent3">
        select * from teacher where id=#{tid}
    </select>
    
    <resultMap id="TeacherStudent3" type="Teacher">
        <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id" />
    </resultMap>

    <select id="getStudentByTeacherId" resultType="Student">
        select  * from  student_2 where tid=#{tid}
    </select>

</mapper>

mybatis-config.xml 文件


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--属性-->
    <properties resource="dbconfig.properties"/>

    <!--设置-->
    <settings>
        <!-- STDOUT_LOGGING 打印到控制台 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!-- 开启驼峰 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!--别名-->
    <typeAliases>
        <!--这是 自己 取别名-->
         <typeAlias alias="Student" type="com.crush.pojo.Student"/>
         <typeAlias alias="Teacher" type="com.crush.pojo.Teacher"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/StudentMapper.xml"/>
        <mapper resource="mapper/TeacherMapper.xml"/>
    </mappers>
</configuration>

测试:



public class MyTest {

    @Test
    public void getTeacher(){
        SqlSession session = MybatisUtil.getSession();

        TeacherMapper mapper = session.getMapper(TeacherMapper.class);

        List<Teacher> teacher = mapper.getTeacher();

        System.out.println(teacher);

        session.close();
    }

    @Test
    public  void getTeacher2(){
        SqlSession session = MybatisUtil.getSession();
        TeacherMapper mapper = session.getMapper(TeacherMapper.class);

        Teacher teacher2 = mapper.getTeacher2(1);
        System.out.println(teacher2);
        session.close();
    }

    @Test
    public  void getTeacher3(){
        SqlSession session = MybatisUtil.getSession();
        TeacherMapper mapper = session.getMapper(TeacherMapper.class);
        Teacher teacher2 = mapper.getTeacher3(1);
        System.out.println(teacher2);
        session.close();
    }
}

以上就是Mybatis结果集映射一对多 的详细内容,更多关于Mybatis结果集映射的资料请关注编程网其它相关文章!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯