MyBatis 进阶(下)

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介: MyBatis 进阶(下)

二、特殊的模糊查询



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


89e463f861c64ebaab77b8af02640b5f.png


方法1


" UserMapper " 接口:


@Mapper
public interface UserMapper {
    // 模糊查询
    public List<UserInfo> fuzzySearch(@Param("username") String username);
}


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.example.demo.mapper.UserMapper">
    <!-- 模糊查询 -->
    <select id="fuzzySearch" resultType="com.example.demo.model.UserInfo">
        select * from userinfo where username like #{username}
    </select>
</mapper>


测试类:


@SpringBootTest
class UserMapperTest {
    @Resource
    private UserMapper userMapper;
    // 模糊查询
    @Test
    void fuzzySearch() {
        String username = "%李%";
        List<UserInfo> list = userMapper.fuzzySearch(username);
        System.out.println("测试结果:" + list);
    }
}


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


20ce945c6754416b8e135e131b2b7e85.png


方法2 (推荐)


引入


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


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


如下所示:


d4b9859801c14816a9ccbc6b3a4f1601.png


代码实现


上述的 UserMapper 接口代码不变。

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


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


测试方法改为如下形式:


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


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


3bec315b5f8a45eca6a07917f9d6b52b.png


三、resultType 和 resultMap



1. 使用 resultType 返回类型


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


0fceecb8849549ddac334cd5cba0843d.png


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


" UserMapper " 接口:


@Mapper
public interface UserMapper {
    // 根据用户 id 来查询某个用户的所有信息
    public UserInfo getUserById(@Param("id") Integer id);
}


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


<?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.example.demo.mapper.UserMapper">
    <!-- 根据用户 id 来查询某个用户的所有信息 -->
    <select id="getUserById" resultType="com.example.demo.model.UserInfo">
        select * from userinfo where id = #{id}
    </select>
</mapper>


测试类:


@SpringBootTest
class UserMapperTest {
    @Resource
    private UserMapper userMapper;
    // 根据用户 id 来查询某个用户的所有信息
    @Test
    void getUserById() {
        UserInfo userInfo = userMapper.getUserById(2);
        System.out.println("测试结果:" + userInfo);
    }
}


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


0b5cb833f3974c9589a6a7d8a8b426ad.png


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


2. 使用 resultMap 返回字典映射


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


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


<?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.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>
    <!--  根据用户 id 来查询某个用户的所有信息 -->
    <select id="getUserById" resultMap="BaseMap">
        select * from userinfo where id = #{id}
    </select>
</mapper>


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


ed3987ce7cee4e32b3678b8cf2f70dc2.png


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


7d89cb20446446ee95135fd4d8d2df63.png


四、 多表查询一对一



我们来看两张表,

一张表是 student 表,表中有 (学生的班级 id,名字,年级 gid,教室)

另一张表是 grade 表,表中有 (学生的年级 gid 和分数)


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

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


f7896b9f445e4f25961c1e7b368d5114.png


1. 使用 resultType 实现


Student 实体类:


@Data
public class Student {
    private int id;
    private String name;
    private int gid;
    private String classroom;
    private Grade grade;
}


Grade 实体类:


@Data
public class Grade {
    private int gid;
    private int score;
}


" StudentMapper " 接口:


@Mapper
public interface StudentMapper {
  // 多表查询,查询分数
    public Student getScore(@Param("id") Integer id);
}


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.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>


测试类:


@SpringBootTest
class StudentMapperTest {
    @Resource
    private StudentMapper studentMapper;
    @Test
    void getScore() {
        Student student = studentMapper.getScore(3);
        System.out.println("查询结果: " + student);
    }
}


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


932e59cc9de845248f0037e5f722fea2.png


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


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


f4453c6e782b45eba8de103d25a4fe79.png


2. 使用 resultMap 实现


Student 实体类:


@Data
public class Student {
    private int id;
    private String name;
    private int gid;
    private String classroom;
    private Grade grade;
}


Grade 实体类:


@Data
public class Grade {
    private int gid;
    private int score;
}


" StudentMapper " 接口:


@Mapper
public interface StudentMapper {
  // 多表查询,查询分数
    public Student getScore(@Param("id") Integer id);
}


StudentMapper.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.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>


GradeMapper.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.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>


测试类:


@SpringBootTest
class StudentMapperTest {
    @Resource
    private StudentMapper studentMapper;
    @Test
    void getScore() {
        Student student = studentMapper.getScore(3);
        System.out.println("查询结果: " + student);
    }
}


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


d27f80f831274dcf80f3cc10e0a5e531.png


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


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


91aa283002914dba9595d4dd0f88ae27.png



resultMap 的缺陷


引入问题


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


a8e75c3343a640c4bbbc9612dcca1c66.png


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


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


解决方案


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


<?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.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>


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


7e171f76a1b84fc3a82c4b141054c6a8.png


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


五、多表查询一对多



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

我们来看两张表,


一张表是 student 表,表中有 (学生的班级 id,名字,年级 gid,教室)

另一张表是 schoolroom 表,表中有 (班级名称和班级总人数)


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

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


1585ee4fb36d4f1f97c8557a44f1f563.png


使用 resultMap 实现


Student 实体类:


@Data
public class Student {
    private int id;
    private String name;
    private int gid;
    private String classroom;
}


Schoolroom 实体类:


@Data
public class Schoolroom {
    private String classname;
    private int total;
    private List<Student> students;
}


" SchoolroomMapper " 接口:


@Mapper
public interface SchoolroomMapper {
    public Schoolroom getStudents(@Param("classname") String classname);
}


SchoolroomMapper.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.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>


StudentMapper.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.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>


测试类:


@SpringBootTest
class SchoolroomMapperTest {
    @Resource
    private SchoolroomMapper schoolroomMapper;
    @Test
    void getStudents() {
        Schoolroom schoolroom = schoolroomMapper.getStudents("2班");
        System.out.println("查询结果: " + schoolroom);
    }
}


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


b36e6b525cee440080d604a024319c55.png


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


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


解决字段重名问题


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


<?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.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>


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


37b20c1d2b324db881dad31134cfea53.png


相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
目录
相关文章
|
11月前
|
SQL Java 数据库连接
MyBatis进阶:掌握MyBatis动态SQL与模糊查询、结果映射
MyBatis进阶:掌握MyBatis动态SQL与模糊查询、结果映射
328 0
|
3月前
|
SQL XML Java
Mybatis进阶——动态SQL(1)
Mybatis进阶——动态SQL(1)
31 3
|
4月前
|
XML Java 数据库连接
【JavaEE进阶】 MyBatis使用XML实现增删改查
【JavaEE进阶】 MyBatis使用XML实现增删改查
|
4月前
|
Java 关系型数据库 数据库连接
【JavaEE进阶】 MyBatis使用注解实现增删改查
【JavaEE进阶】 MyBatis使用注解实现增删改查
|
4月前
|
Java 关系型数据库 数据库连接
【JavaEE进阶】MyBatis⼊⻔
【JavaEE进阶】MyBatis⼊⻔
|
12月前
|
SQL Java 数据库连接
MyBatis进阶:掌握MyBatis动态SQL与模糊查询、结果映射,让你在面试中脱颖而出!!
MyBatis进阶:掌握MyBatis动态SQL与模糊查询、结果映射,让你在面试中脱颖而出!!
179 0
|
4月前
|
SQL XML Java
【JavaEE进阶】 MyBatis之动态SQL
【JavaEE进阶】 MyBatis之动态SQL
|
11月前
|
SQL Java 数据库连接
“MyBatis进阶:分页与特殊字符处理“
“MyBatis进阶:分页与特殊字符处理“
40 0
|
12月前
|
SQL XML Java
MyBatis进阶:告别SQL注入!MyBatis分页与特殊字符的正确使用方式
MyBatis进阶:告别SQL注入!MyBatis分页与特殊字符的正确使用方式
270 0
|
SQL Java 程序员
Mybatis-Plus 进阶开发 -- Mybatis-Plus 入门教程(二)(3)
Mybatis-Plus 进阶开发 -- Mybatis-Plus 入门教程(二)
134 0