MyBatis学习-(六)解决列名和属性名不同问题和模糊查询

本文最后更新于:January 21, 2022 am

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

目录

MyBatis 中文文档:https://mybatis.org/mybatis-3/zh/index.html

当数据库列名和Java对象属性名不同时,我们可以使用resultMap。实际在相同的情况下也可以使用,只是resultMap和resultType不能同时使用,二选一即可。

resultMap

自定义类

1
2
3
4
5
public class Student {
private String cid;
private String cname;
private int age;
}

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
26
27
28
29
30
31
32
<?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.tothefor.dao.StudentDao">

<select id="queryByName" resultType="com.tothefor.entity.Student">
select * from Student where name = #{name}
</select>


<!-- 这里的id自定义名称,type是返回类型的类-->
<resultMap id="mytest" type="com.tothefor.entity.Student">
<!-- 定义列名和属性名的对应关系 -->
<!-- 主键类型使用id标签-->
<id column="id" property="cid"></id>
<!-- 非主键类型使用result标签-->
<result column="name" property="cname"></result>
<!-- 当列名和属性名相同时,可定义也可不定义-->
<result column="age" property="age"></result>
</resultMap>
<!-- 使用resultMap属性指定映射关系的id-->
<select id="queryByName" resultMap="mytest">
select id,name,age from Student where name = #{name}
</select>
<!-- 可以复用 -->
<select id="queryByName2" resultMap="mytest">
select id,name,age from Student where name = #{name}
</select>

</mapper>

resultType

这中方式中使用列名的别名即可。所以,要求就是列的别名是和类的中属性名一样。

1
2
3
<select id="queryByName2" resultMap="mytest">
select cid,cname,age from Student where name = #{name}
</select>

这种方式不太推荐,推荐使用第一种。

模糊查询

思想都是在查询的字符串前后加上百分号(%)。所以第一种就是给查询的字符串拼上百分号,这种就不演示了。只说MyBatis中怎么用mapper文件实现。

1
2
3
<select id="queryByName" resultType="com.tothefor.entity.Student">
select * from Student where name like "%" #{name} "%"
</select>

注意百分号前后的空格。