• MyBatis 进阶


    引言

    本篇博客是接着上一篇博客所写的,上一篇博客主要介绍了 MyBatis 的增删改查,本篇博客主要介绍 MyBatis 在增删改查上的一些细节。

    上一篇博客链接

    一、#{} 和 ${} 的区别

    我们准备好一个 userinfo 表,并测试两种符号。

    1-1

    1. 通过 id 查询用户信息

    (1) #{id}

    " UserMapper " 接口:

    @Mapper
    public interface UserMapper {
    
        // 根据用户 id 来查询某个用户的所有信息
        public UserInfo getUserById(@Param("id") Integer id);
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    xml 文件 ( 使用 #{} 占位符 )

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.UserMapper">
    
        
        <select id="getUserById" resultType="com.example.demo.model.UserInfo">
            select * from userinfo where id = #{id}
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试类:

    @SpringBootTest
    class UserMapperTest {
    
        @Resource
        private UserMapper userMapper;
    
        // 根据用户 id 来查询某个用户的所有信息
        @Test
        void getUserById() {
            UserInfo userInfo = userMapper.getUserById(2);
            System.out.println("测试结果:" + userInfo);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    启动测试方法,查看 MyBatis 日志打印:

    1-2

    (2) ${id}

    改变 " xml 文件 " 代码,UserMapper 接口和测试方法不进行改变。

    <select id="getUserById" resultType="com.example.demo.model.UserInfo">
        select * from userinfo where id = ${id}
    select>
    
    • 1
    • 2
    • 3

    启动测试方法,查看 MyBatis 日志打印:

    1-3

    初步结论

    从两个 MyBatis 日志打印的结果来看,我们可以看出

    #{} 符,它是先用问号进行预处理,之后再使用参数替换的
    ${} 符,它是直接对查询参数替换的

    2. 通过 username 查询用户信息

    (1) #{username}

    " UserMapper " 接口:

    @Mapper
    public interface UserMapper {
    
        // 根据用户 username 来查询某个用户的所有信息
        public UserInfo getUserByUsername(@Param("username") String username);
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    xml 文件 ( 使用 #{} 占位符 )

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.UserMapper">
    
        
        <select id="getUserByUsername" resultType="com.example.demo.model.UserInfo">
            select * from userinfo where username = #{username}
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试类:

    @SpringBootTest
    class UserMapperTest {
    
        @Resource
        private UserMapper userMapper;
    
        // 6. 根据用户 username 来查询某个用户的所有信息
        @Test
        void getUserByUsername() {
            UserInfo userInfo = userMapper.getUserByUsername("李明");
            System.out.println("测试结果:" + userInfo);
        }
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    启动测试方法,查看 MyBatis 日志打印:

    1-4

    (2) ${username}

    改变 " xml 文件 " 代码,UserMapper 接口和测试方法不进行改变。

    <select id="getUserByUsername" resultType="com.example.demo.model.UserInfo">
        select * from userinfo where username = ${username}
    select>
    
    • 1
    • 2
    • 3

    启动测试方法,查看 MyBatis 日志打印:

    1-5

    结论

    从两个 MyBatis 日志打印的结果来看,我们可以看出

    #{} 符,在预处理后,它是可以自动为字符串类型加上单引号的。
    ${} 符,它是直接进行字符串替换的。

    两个符号的转换过程,对比如下:

    1-6

    数据库验证:

    1-7

    经过数据库验证后,我们发现 ${} 符直接替换字符串是不合理的。说到底,从数据库角度看,就是语法问题而已。

    3. 通过创建时间对用户进行排序

    数据库提供字段值的临时排序有两种,一是升序,二是降序。

    1-8

    (1) #{order}

    " UserMapper " 接口:

    @Mapper
    public interface UserMapper {
    
        // 通过创建时间对用户进行排序
        public List<UserInfo> sortByTime(@Param("order") String order);
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    xml 文件 ( 使用 #{} 占位符 )

    备注: 虽然这里返回值是 List,但是 List 中的存的值依然是 UserInfo,所以我们依然可以将 resultType 设置为 UserInfo

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.UserMapper">
    
        
        <select id="sortByTime" resultType="com.example.demo.model.UserInfo">
            select * from userinfo order by createtime #{order}
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试类:

    @SpringBootTest
    class UserMapperTest {
    
        @Resource
        private UserMapper userMapper;
    
        // 通过创建时间对用户进行排序
        @Test
        void sortByTime() {
            List<UserInfo> list = userMapper.sortByTime("asc");
            System.out.println("测试结果: " + list);
        }
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    启动测试方法,查看 MyBatis 日志打印:

    2-1

    (2) ${order}

    改变 " xml 文件 " 代码,UserMapper 接口和测试方法不进行改变。

    <select id="sortByTime" resultType="com.example.demo.model.UserInfo">
        select * from userinfo order by createtime ${order}
    select>
    
    • 1
    • 2
    • 3

    启动测试方法,查看 MyBatis 日志打印:

    2-2

    结论

    从两个 MyBatis 日志打印的结果来看,我们可以看出

    #{} 符,在预处理后,它是可以自动为字符串类型加上单引号的,但它不是智能的,它无法检测我们预期查询的参数是否是数据库的一些关键字。 所以在有些场景下,它无脑加上单引号,并不会产生正确的结果。

    ${} 符,它是直接进行字符串替换的。同样地,它也不是智能的,它也是无脑进行替换的。

    两个符号的转换过程,对比如下:

    2-3

    数据库验证:

    2-4

    4. ${} 产生的 SQL 注入问题

    引入

    之前我们说,#{} 是可以预处理的,${} 是直接替换参数的。那么,如果我们手动将参数加上单引号,那么类似于这样的 ’ ${} ’ 就可以和 #{} 等价了 ( 暂且视为等价 )。

    下面我们就通过模拟登录的方式来验证此情况,我们预期通过账号和密码查询 " 李明 " 用户的全部信息。

    2-5

    2-6

    (1) 测试

    " UserMapper " 接口:

    @Mapper
    public interface UserMapper {
    
        // 登录解析 SQL 注入的问题
        public UserInfo login(@Param("username") String username, @Param("password") String password);
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    xml 文件 ( 使用 #{} 占位符 )

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.UserMapper">
    
        
        <select id="login" resultType="com.example.demo.model.UserInfo">
            select * from userinfo where username = '${username}' and password = '${password}'
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试类:

    @SpringBootTest
    class UserMapperTest {
    
        @Resource
        private UserMapper userMapper;
    
        // 登录解析 SQL 注入的问题
        @Test
        void login() {
            String username = "李明";
            String password = "321";
    
            UserInfo userInfo = userMapper.login(username, password);
            System.out.println("测试结果:" + userInfo);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    启动测试方法,查看 MyBatis 日志打印:

    2-7

    初步结论: 从上面的结果看,好像确实没什么问题,但实际它隐含了一个安全问题,请继续往下看。

    (2) 改变测试内容

    上面的接口和 " xml 文件 " 不作改变,我们修改测试类的 password 参数:

    @Test
    void login() {
        String username = "李明";
        String password = " ' = ' ";
    
        UserInfo userInfo = userMapper.login(username, password);
        System.out.println("测试结果:" + userInfo);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    启动测试方法,查看 MyBatis 日志打印:

    2-8

    观察上面的打印日志时,其实我们就发现问题了,就算我们输入的是一个错误的密码,也能够获取一个用户的所有参数。 如果此漏洞出现在了线上环境下,这其实是很危险的!当下的互联网时代,钱就是数据,数据就是钱。那么如果数据内容被盗,损失是很大的。

    (3) 使用 #{} 测试当前 SQL 注入问题

    将 xml 文件中的 SQL 语句,改为 #{} 符号,继续测试错误的密码:

    <select id="login" resultType="com.example.demo.model.UserInfo">
        select * from userinfo where username = #{username} and password = #{password}
    select>
    
    • 1
    • 2
    • 3

    启动测试方法,查看 MyBatis 日志打印:

    2-9

    可以发现,使用 #{} 查询的结果为空,这就说明 #{} 没有安全漏洞。
    因为它的转换过程如下所示:

    2-10

    结论

    ${} 号的应用,会带来 SQL 注入问题,也就是说,SQL 注入是一个安全问题。

    上面的情况只是 SQL 注入的其中一种场景而已,如果前端真的传来一个参数,能够破解一个用户的身份信息,这是很危险的。实际上,黑客能够利用 ${} 的简单漏洞,来暴力破解数据信息。

    而造成这种情况的主要原因就是,数据库中的字符串是由单引号将数据包裹起来的,Java 的字符串是用双引号包裹起来的,所以如何将参数放到一个 SQL 语句中,这就是一个难点。然而,MyBatis 提供的 ${} 直接替换参数,本质上,替换参数是用户自己写的参数。这就带来了一个问题:我们永远猜不到用户输入的是什么。

    所以,一般情况下,对于一个正常的参数,我们应该使用 #{},对于一个关键字,应该使用 ${},然而,使用 ${} 之前,就一定要对前端传入的参数值进行安全校验。

    5. 最终的结论

    ① #{} 是预处理机制,而 ${} 是直接替换。

    ② #{} 适用于一个正常参数的匹配,但 ${} 只适用数值类型和数据库关键字。

    ③ #{} 没有安全问题,但 ${} 存在 SQL 注入的安全漏洞。

    ④ 不管是 #{} 还是 ${},最重要的还是 SQL 语句。因为说白了,两个符号都是基于 SQL 的语法而设定的,正是因为后端程序和数据库之间需要沟通,所以才会出现这样的桥梁。

    二、特殊的模糊查询

    我们预期从 userinfo 表中,查出 username 包含 " 李 " 字的所有用户信息。

    3-1

    方法1

    " UserMapper " 接口:

    @Mapper
    public interface UserMapper {
    
        // 模糊查询
        public List<UserInfo> fuzzySearch(@Param("username") String username);
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    xml 文件 ( 使用 #{} 占位符 )

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.UserMapper">
    
        
        <select id="fuzzySearch" resultType="com.example.demo.model.UserInfo">
            select * from userinfo where username like #{username}
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试类:

    @SpringBootTest
    class UserMapperTest {
    
        @Resource
        private UserMapper userMapper;
    
        // 模糊查询
        @Test
        void fuzzySearch() {
            String username = "%李%";
            List<UserInfo> list = userMapper.fuzzySearch(username);
            System.out.println("测试结果:" + list);
        }
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    启动测试方法,查看 MyBatis 日志打印:

    3-2

    方法2 (推荐)

    引入

    在方法1 中,前端需要无脑地将 ’ %李% ’ 中的 % 也要传入到 SQL 语句中,但实际上,前端并不会这么做,通常情况下,他们只会传一个 ’ 李 ’ 给后端。所以我们就要通过 方法2 自己实现字符的拼接。

    我们希望方法2 省去了前端传入的 ’ % ’ 参数,利用 MySQL 数据库内置的 concat ,来合理拼接 ’ % ’ ,这样一来,前端只需要传入想要检索的值即可。实际上,concat 在这里就是起到了拼接字符的作用,它同样可以用来拼接字符串。

    如下所示:

    3-3

    代码实现

    上述的 UserMapper 接口代码不变。

    " xml 文件 " 改为如下形式:

    <select id="fuzzySearch" resultType="com.example.demo.model.UserInfo">
    
        select * from userinfo where username like concat ('%', #{username}, '%');
        
    select>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    测试方法改为如下形式:

    @Test
    void fuzzySearch() {
        String username = "李";
        List<UserInfo> list = userMapper.fuzzySearch(username);
        System.out.println("测试结果:" + list);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    启动测试方法,查看 MyBatis 日志打印:

    3-4

    三、resultType 和 resultMap

    1. 使用 resultType 返回类型

    我们准备一个 userinfo 表和一个 Userinfo 实体类,并故意将两者的用户名字设置为不一样,看看到最后 " u_name " 是否能接收到 " username " 的值数据。

    3-5

    @Data
    public class UserInfo {
        private int id;
        private String u_name; // 这里进行改变
        private String password;
        private String photo;
        private String createtime;
        private String updatetime;
        private int state;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    " UserMapper " 接口:

    @Mapper
    public interface UserMapper {
    
        // 根据用户 id 来查询某个用户的所有信息
        public UserInfo getUserById(@Param("id") Integer id);
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在 xml 文件中,select 标签我们使用 resultType

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.UserMapper">
    
        
        <select id="getUserById" resultType="com.example.demo.model.UserInfo">
            select * from userinfo where id = #{id}
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试类:

    @SpringBootTest
    class UserMapperTest {
    
        @Resource
        private UserMapper userMapper;
    
        // 根据用户 id 来查询某个用户的所有信息
        @Test
        void getUserById() {
            UserInfo userInfo = userMapper.getUserById(2);
            System.out.println("测试结果:" + userInfo);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    启动测试方法,查看 MyBatis 日志打印:

    3-6

    初步结论: 使用 resultType 作为返回类型的时候,实体类的属性 (成员变量),经写死之后,就不能更改了。一般来说,实体类的属性如果写成和数据表的字段不同名的情况,那么就无法映射成功,属性自然就为空值了。当前场景下的最终情况,前端就拿不到 username 的字段值了。

    2. 使用 resultMap 返回字典映射

    对于上面的接口和测试方法不改变的情况下,改变 " xml 文件 " 代码:

    在 xml 文件中,select 标签我们使用 resultMap

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.UserMapper">
    
        <resultMap id="BaseMap" type="com.example.demo.model.UserInfo">
            
            <id column="id" property="id">id>
            
            <result column="username" property="u_name">result>
        resultMap>
    
        
        <select id="getUserById" resultMap="BaseMap">
            select * from userinfo where id = #{id}
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    启动测试方法,查看 MyBatis 日志打印:

    3-7

    结论: resultMap 可以根据实体类来自定义接收属性名,前提是我们在 resultMap 标签中声明了 column,property.

    3-8

    四、 多表查询一对一

    我们来看两张表,
    一张表是 student 表,表中有 (学生的班级 id,名字,年级 gid,教室)
    另一张表是 grade 表,表中有 (学生的年级 gid 和分数)

    我们预期通过 student 表中的 gid 来查询某个学生的分数。这就需要借助于多表查询,其中学生表中 gid 和 年级表中的 gid 呈一对一关系。

    如下图所示,我们借助于下面的 select 语句,将两张表关联起来。

    3-9

    1. 使用 resultType 实现

    Student 实体类:

    @Data
    public class Student {
        private int id;
        private String name;
        private int gid;
        private String classroom;
        private Grade grade;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Grade 实体类:

    @Data
    public class Grade {
        private int gid;
        private int score;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    " StudentMapper " 接口:

    @Mapper
    public interface StudentMapper {
    	
    	// 多表查询,查询分数
        public Student getScore(@Param("id") Integer id);
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    xml 文件

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.StudentMapper">
    
        
        <select id="getScore" resultType="com.example.demo.model.Student">
            select * from student, grade where student.gid = grade.gid and student.id = #{id}
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试类:

    @SpringBootTest
    class StudentMapperTest {
    
        @Resource
        private StudentMapper studentMapper;
    
        @Test
        void getScore() {
            Student student = studentMapper.getScore(3);
            System.out.println("查询结果: " + student);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    启动测试方法,查看 MyBatis 日志打印:

    4-1

    结论: 在 " xml 文件 " 中使用 resultType 作为返回值,代码固然没有出错,但是它并不适用于多表联查。

    原因很简单,resultType 只能指定一个实体类作为字段的返回值,如果多表联查的时候,不指定另外的实体类,那么 MyBatis 框架就没法帮我们映射字段值到类的属性之中。

    4-2

    2. 使用 resultMap 实现

    Student 实体类:

    @Data
    public class Student {
        private int id;
        private String name;
        private int gid;
        private String classroom;
        private Grade grade;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Grade 实体类:

    @Data
    public class Grade {
        private int gid;
        private int score;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    " StudentMapper " 接口:

    @Mapper
    public interface StudentMapper {
    	
    	// 多表查询,查询分数
        public Student getScore(@Param("id") Integer id);
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    StudentMapper.xml 文件

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.StudentMapper">
        
        <resultMap id="StudentBaseMap" type="com.example.demo.model.Student">
            
            <id column="id" property="id">id>
            
            <result column="name" property="name">result>
            <result column="gid" property="gid">result>
            <result column="classroom" property="classroom">result>
            <association property="grade"
                         resultMap="com.example.demo.mapper.GradeMapper.GradeBaseMap">
            association>
        resultMap>
    
        <select id="getScore" resultMap="StudentBaseMap">
            select * from student, grade where student.gid = grade.gid and student.id = #{id}
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    GradeMapper.xml 文件

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.GradeMapper">
    
        <resultMap id="GradeBaseMap" type="com.example.demo.model.Grade">
            
            <id column="gid" property="gid">id>
            
            <result column="score" property="score">result>
        resultMap>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    测试类:

    @SpringBootTest
    class StudentMapperTest {
    
        @Resource
        private StudentMapper studentMapper;
    
        @Test
        void getScore() {
            Student student = studentMapper.getScore(3);
            System.out.println("查询结果: " + student);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    启动测试方法,查看 MyBatis 日志打印:

    4-3

    结论: 使用 resultMap 能够使用多表联查,但这需要多个 " xml 文件 " 支持才行,不同的 " xml 文件 " 对应着不同的实体类,也对应着不同的 Mapper 接口。

    两个 " xml 文件 " 之间的关系如下,一对一的多表查询是通过 association 标签来实现多表之间的互联。

    4-4

    resultMap 的缺陷

    引入问题

    使用 resultMap 时有一个缺陷,当多表查询时,若两张表的字段名相同时,可能会出现这样的情况:【前一个表的字段值覆盖后一个表的字段值】,这样一来就会造成查询不准确的结果。

    4-5

    所以,我们平时在一个项目中设计的表,最好不要将两张有关联的表设计成相同的字段,这样就会带来重名的问题。其一就是容易混淆,其二就是上面所说的覆盖问题。

    但实际上,如果我们在工作中查询的是公司的数据表,数据表中又出现这样的重名情况,我们不可能对原有的数据库做出更改,所以我们只能对 " xml 文件 " 做出一些修改,解决方案如下所示:

    解决方案

    其余的所有代码不变,只为 StudentMapper.xml 文件设置 columnPrefix 属性

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.StudentMapper">
        
        <resultMap id="StudentBaseMap" type="com.example.demo.model.Student">
            
            <id column="id" property="id">id>
            
            <result column="name" property="name">result>
            <result column="gid" property="gid">result>
            <result column="classroom" property="classroom">result>
            <association property="grade"
                         resultMap="com.example.demo.mapper.GradeMapper.GradeBaseMap"
                         columnPrefix="g_">
    
            association>
        resultMap>
    
        <select id="getScore" resultMap="StudentBaseMap">
    		select student.*, grade.gid g_gid, grade.score g_score from student, grade 
    				where student.gid = grade.gid and student.id = #{id}
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    启动测试方法,查看 MyBatis 日志打印:

    4-6

    结论: 在 " xml 文件 " 中,association 标签为我们提供的三个属性 property、resultMap、columnPrefix,前两者是必须要使用的,最后一个酌情使用。

    五、多表查询一对多

    备注: 上面介绍了一对一关系的查询,我们先将一对一关系全部忘干净,再来看看一对多查询的关系。

    我们来看两张表,
    一张表是 student 表,表中有 (学生的班级 id,名字,年级 gid,教室)
    另一张表是 schoolroom 表,表中有 (班级名称和班级总人数)

    我们预期通过班级名称参数,来寻找学生表中属于此参数的学生信息。这就需要借助于多表查询,其中 schoolroom 表中 classname 和 student 表中的 classroom 呈一对多关系。

    如下图所示,我们借助于下面的 select 语句,将两张表关联起来。

    4-7

    使用 resultMap 实现

    Student 实体类:

    @Data
    public class Student {
        private int id;
        private String name;
        private int gid;
        private String classroom;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    Schoolroom 实体类:

    @Data
    public class Schoolroom {
        private String classname;
        private int total;
        private List<Student> students;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    " SchoolroomMapper " 接口:

    @Mapper
    public interface SchoolroomMapper {
    
        public Schoolroom getStudents(@Param("classname") String classname);
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    SchoolroomMapper.xml 文件

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.SchoolroomMapper">
    
        <resultMap id="SchoolBaseMap" type="com.example.demo.model.Schoolroom">
            
            <result column="classname" property="classname">result>
            <result column="total" property="total">result>
            <collection property="students"
            			resultMap="com.example.demo.mapper.StudentMapper.StudentBaseMap">
    
            collection>
        resultMap>
    
        <select id="getStudents" resultMap="SchoolBaseMap">
            select * from schoolroom, student
                    where schoolroom.classname = student.classroom and schoolroom.classname = #{classname}
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    StudentMapper.xml 文件

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.StudentMapper">
        
        <resultMap id="StudentBaseMap" type="com.example.demo.model.Student">
            
            <id column="id" property="id">id>
            
            <result column="name" property="name">result>
            <result column="gid" property="gid">result>
            <result column="classroom" property="classroom">result>
        resultMap>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    测试类:

    @SpringBootTest
    class SchoolroomMapperTest {
    
        @Resource
        private SchoolroomMapper schoolroomMapper;
    
        @Test
        void getStudents() {
            Schoolroom schoolroom = schoolroomMapper.getStudents("2班");
            System.out.println("查询结果: " + schoolroom);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    启动测试方法,查看 MyBatis 日志打印:

    4-8

    结论: 关于一对多的多表查询问题,resutlMap 为我们专门提供了 collection 标签,collection 标签常用于指定实体类中的 " List 类型的成员变量 "。

    collection 常用的属性有三个: property、resultMap、columnPrefix. 前两者是必须要使用的,最后一个是用于防止两个表字段重名冲突的情况。

    解决字段重名问题

    其余的所有代码不变,只为 StudentMapper.xml 文件设置 columnPrefix 属性

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.demo.mapper.SchoolroomMapper">
    
        <resultMap id="SchoolBaseMap" type="com.example.demo.model.Schoolroom">
            
            <result column="classname" property="classname">result>
            <result column="total" property="total">result>
            <collection property="students"
            			resultMap="com.example.demo.mapper.StudentMapper.StudentBaseMap"
            			columnPrefix="s_">
    
            collection>
        resultMap>
    
        <select id="getStudents" resultMap="SchoolBaseMap">
        
        select schoolroom.* ,
            student.id s_id, student.name s_name, student.gid s_gid, student.classroom s_classroom
            from schoolroom, student
            where schoolroom.classname = student.classroom and schoolroom.classname = #{classname}
            
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    启动测试方法,查看 MyBatis 日志打印:

    4-9

  • 相关阅读:
    【C语言】预处理详解,宏与函数的区别对比
    面试题库(八):docker和linux
    扩散模型实战(九):使用CLIP模型引导和控制扩散模型
    窗口期即将关闭,谁在跑出车规级AI芯片的创新“超速度”?
    【MATLAB】制作一幅钻石沿着圆周运动的动画
    Web前端面试之Vue—对Vue的理解
    【vue3】实现筛选页组件(深层嵌套循环数据切换)的封装和调用
    区分axios在开发环境和生产环境的请求基础地址
    什么是语句?什么是表达式?
    解决 matplotlib 中文字体无法显示问题
  • 原文地址:https://blog.csdn.net/lfm1010123/article/details/127256485