MyBatis标签及其应用示例
1. select
1.1 标签属性
id | 唯一的标识符 |
parameterType | 传给此语句的参数的全路径名或别名如:com.xxx.xxx.demo.entity.User或user |
resultType | 语句返回值类型或别名。如果是集合List,此处填写集合的泛型T,而不是集合本身。同时,resultType 与resultMap 只能用一个。此外, |
2.1 应用示例
<select id="selectUserlist" parameterType="string" resultType="com.xxx.xxx.demo.entity.User">select * from user where name = #{name}</select>
2.1.1 resultType到底该填啥
resultType:
基本类型 | resultType=‘基本类型’ |
List类型 | resultType=‘List中元素的类型即List中的T’ |
Map类型 | resultType =‘map’ |
2. insert
2.1 标签属性
id | 唯一的标识符 |
parameterType | 传给此语句的参数如 com.xxx.xxx.demo.entity.User |
2.2 应用示例
2.2.1 常规应用
<insert id="insertUser" parameterType="com.xxxx.xxxx.demo.entity.User">insert into user (name, age, email) values (#{name}, #{age}, #{email})</insert>
2.2.2 插入后返回主键
增加以下两个可以获取(获取方式:通过对象的get方法)刚刚插入数据库数据的主键如id
useGeneratedKeys=“true” 使用生成的主键
keyProperty="" 查询的主键名,主键字段对应实体类的属性,一般为id
<insert id="insertUser" parameterType="com.xxxxx.xxx.demo.entity.User" useGeneratedKeys="true" keyProperty="id">insert into user (name, age, email)values (#{name},#{age},#{email})</insert>
2.2.3 插入多条数据
配合foreach标签使用:
<insert id="insertUsers" parameterType="com.xxx.xxx.demo.entity.User">insert into user (name, age, email)values <foreach collection="list" item="item" separator=",">(#{item.name},#{item.age},#{item.email})</foreach>
3. delete
3.1 标签属性
id | 唯一的标识符 |
parameterType | 传给此语句的参数如 int |
3.2 应用示例
3.2.1 删除一条记录
<delete id="deleteUser" parameterType="integer">delete from user where id = #{id}</delete>
3.2.2 删除多条数据(批量删除)
<delete id="deleteUsers" parameterType="integer">delete from userwhere id in<foreach collection="array" item="id" open="(" close=")" separator=",">#{id}</foreach></delete>
4. update
4.1 标签属性
id | 唯一的标识符 |
parameterType | 传给此语句的参数如 com.xxx.xxx.demo.entity.User |
4.2 应用示例
<update id="updateUser" parameterType="com.xxx.xxx.demo.entity.User">update user set name=#{name},age=#{age},email=#{email} where id=#{id}</update>
resultMap
主要作用是为了建立SQL查询结果字段与实体属性的映射关系信息。查询的结果集转换为java对象,方便进一步操作。
PS:与java对象对应的列不是数据库中表的列名,而是查询后结果集的列名。
<resultMap id="BaseResult" type="com.xxx.xxx.demo.entity.User">
属性 | 描述 |
---|---|
id | 当前命名空间中的一个唯一标识,用于标识一个结果映射。 |
type | 类的完全限定名, 或者一个类型别名(关于内置的类型别名,可以参考上面的表格)如: com.xxx.xxx.demo.entity.User。 |
autoMapping | 如果设置这个属性,MyBatis 将会为本结果映射开启或者关闭自动映射。 这个属性会覆盖全局的属性 autoMappingBehavior。默认值:未设置(unset)。 |
extends | 继承其他 resultMap 标签(通常 resultMap 标签都代表了一个实体类,在多表联查时候,如果都需要配置 resultMap 的话,子类的 resultMap 就可以继承父类的 resultMap,然后父类有的那一部分属性标签(id、result标签)就不用在重写了) |
id 和 result 元素都将一个列的值映射到一个简单数据类型(String, int, double, Date 等)的属性或字段。
<resultMap id="BaseResult" type="com.xxx.xxx.demo.entity.User"><id property="id" column="id" javaType="Integer"/><result property="name" column="name" javaType="String"/><result property="age" column="age" javaType="Integer"/><result property="email" column="email" javaType="String"/></resultMap>
property | 对应实体类的属性 |
column | 数据库中的列名,或者是列的别名 |
javaType | 对应java的数据类型,MyBatis 通常可以推断类型。如果要映射到的是 HashMap,需要明确地指定 javaType |
association标签
association 标签:用于一对一、多对一场景使用
标签属性
属性 | 描述 |
---|---|
property | 配置实体类属性名 |
javaType | 指定封装结果的类型。当使用 select 属性时,无需指定关联的类型,结果会直接封装到调用的查询语句中 |
column | 配置数据库列名,搭配 select 属性使用,从第一条 SQL 中获取当前指定字段的内容,在将该内容传入 select 属性调用的 SQL 中 |
select | 使用另一个select查询封装的结果。当使用该属性时,无需配置实体类与数据库之间的映射关系 |
association需要我们告知MyBatis 如何加载关联。MyBatis 提供2种不同的方式加载关联:
嵌套 Select 查询 | 通过执行另外一个 SQL 映射语句来加载期望的复杂类型 |
嵌套结果映射 | 使用嵌套的结果映射来处理连接结果的重复子集 |
/*** 通过id查询商品名记录* @param id* @return*/String selectShopName(Integer id);/*** 查询符合条件的数据记录* @return*/List<User> selectUser();
<resultMap id="BaseResult" type="cjw.study.mybatis.demo.entity.User"><id property="id" column="id" javaType="Integer"/><result property="name" column="name" javaType="String"/><result property="age" column="age" javaType="Integer"/><result property="email" column="email" javaType="String"/><association property="shopname" column="id" javaType="string" select="selectShopName"/></resultMap><select id="selectShopName" parameterType="integer" resultMap="RecordResult">select shopnamefrom record<where><if test="id != '' and id != null">id = #{id}</if></where></select>
@Testpublic void selectUser() { userMapper.selectUser();}
JDBC Connection [HikariProxyConnection@1131673199 wrapping com.mysql.cj.jdbc.ConnectionImpl@399ca607] will not be managed by Spring
==> Preparing: select id, name, age, email from user
==> Parameters:
<== Columns: id, name, age, email
<== Row: 7, Jack, 20, test2@baomidou.com
====> Preparing: select shopname from record WHERE id = ?
====> Parameters: 7(Integer)
<==== Columns: shopname
<==== Row: pc
<==== Total: 1
====> Preparing: select id, shopname, num from record WHERE id = ?
====> Parameters: 7(Long)
<==== Columns: id, shopname, num
<==== Row: 7, pc, 20
<==== Total: 1
<== Row: 8, Tom, 28, test3@baomidou.com
====> Preparing: select shopname from record WHERE id = ?
====> Parameters: 8(Integer)
<==== Columns: shopname
<==== Row: ipad
<==== Total: 1
====> Preparing: select id, shopname, num from record WHERE id = ?
====> Parameters: 8(Long)
<==== Columns: id, shopname, num
<==== Row: 8, ipad, 28
<==== Total: 1
<== Row: 9, Sandy, 21, test4@baomidou.com
====> Preparing: select shopname from record WHERE id = ?
====> Parameters: 9(Integer)
<==== Columns: shopname
<==== Row: car
<==== Total: 1
====> Preparing: select id, shopname, num from record WHERE id = ?
====> Parameters: 9(Long)
<==== Columns: id, shopname, num
<==== Row: 9, car, 21
<==== Total: 1
<== Row: 10, Billie, 24, test5@baomidou.com
====> Preparing: select shopname from record WHERE id = ?
====> Parameters: 10(Integer)
<==== Columns: shopname
<==== Row: shoe
<==== Total: 1
====> Preparing: select id, shopname, num from record WHERE id = ?
====> Parameters: 10(Long)
<==== Columns: id, shopname, num
<==== Row: 10, shoe, 24
<==== Total: 1
<== Row: 13, zbd, 22, cjw.163
====> Preparing: select shopname from record WHERE id = ?
====> Parameters: 13(Integer)
<==== Total: 0
====> Preparing: select id, shopname, num from record WHERE id = ?
====> Parameters: 13(Long)
<==== Total: 0
<== Row: 14, cjw, 22, cjw.163
====> Preparing: select shopname from record WHERE id = ?
====> Parameters: 14(Integer)
<==== Total: 0
====> Preparing: select id, shopname, num from record WHERE id = ?
====> Parameters: 14(Long)
<==== Total: 0
<== Total: 6
collection标签
一对多,多对多是使用,即对应多条数据结果如list、map等时使用。
<collection property="record" column="id" select="selectRecords" ofType="com.xxx.xxx.demo.entity.Record"/>
collection 标签属性:
属性 | 描述 |
---|---|
property | 实体类属性名 |
select | 使用另一个select查询封装的结果。当使用该属性时,便不需要在配置实体类与数据库之间的映射关系了 |
column | 为数据库中的列名,与select配合使用 |
ofType | 指定集合中的泛型信息 ofType = List中的T |
比如select查询条件为id = #{id},则设置colunm = ‘id’。找到购买人与商品的关系,查询商品表中对应的购买人id。
/*** 根据id查询对应的记录* @return*/List<Record> selectRecords(Integer id);/*** 查询符合条件的数据记录* @return*/List<User> selectUser();
<resultMap id="BaseResult" type="com.xxx.xxx.demo.entity.User"><id property="id" column="id" javaType="Integer"/><result property="name" column="name" javaType="String"/><result property="age" column="age" javaType="Integer"/><result property="email" column="email" javaType="String"/><collection property="record" column="id" select="selectRecords" ofType="com.xxx.xxx.demo.entity.Record"/></resultMap><resultMap id="RecordResult" type="com.xxx.xxx.demo.entity.Record"><id property="id" column="id" javaType="Integer"/><result property="shopname" column="name" javaType="String"/><result property="num" column="age" javaType="Integer"/></resultMap><sql id="RecordCol">id, shopname, num</sql><select id="selectRecords" resultMap="RecordResult">select <include refid="RecordCol"></include>from record<where><if test="id != '' and id != null">id = #{id}</if></where></select>
@Testpublic void selectUser() { userMapper.selectUser();}
JDBC Connection [HikariProxyConnection@1141984159 wrapping com.mysql.cj.jdbc.ConnectionImpl@76bf1bb8] will not be managed by Spring
==> Preparing: select id, name, age, email from user
==> Parameters:
<== Columns: id, name, age, email
<== Row: 7, Jack, 20, test2@baomidou.com
====> Preparing: select id, shopname, num from record WHERE id = ?
====> Parameters: 7(Long)
<==== Columns: id, shopname, num
<==== Row: 7, pc, 20
<==== Total: 1
<== Row: 8, Tom, 28, test3@baomidou.com
====> Preparing: select id, shopname, num from record WHERE id = ?
====> Parameters: 8(Long)
<==== Columns: id, shopname, num
<==== Row: 8, ipad, 28
<==== Total: 1
<== Row: 9, Sandy, 21, test4@baomidou.com
====> Preparing: select id, shopname, num from record WHERE id = ?
====> Parameters: 9(Long)
<==== Columns: id, shopname, num
<==== Row: 9, car, 21
<==== Total: 1
<== Row: 10, Billie, 24, test5@baomidou.com
====> Preparing: select id, shopname, num from record WHERE id = ?
====> Parameters: 10(Long)
<==== Columns: id, shopname, num
<==== Row: 10, shoe, 24
<==== Total: 1
<== Row: 13, zbd, 22, cjw.163
====> Preparing: select id, shopname, num from record WHERE id = ?
====> Parameters: 13(Long)
<==== Total: 0
<== Row: 14, cjw, 22, cjw.163
====> Preparing: select id, shopname, num from record WHERE id = ?
====> Parameters: 14(Long)
<==== Total: 0
<== Total: 6
foreach
foreach标签主要用于构建in条件,他可以在sql中对集合进行迭代。
collection | collection属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合 |
item | 表示在迭代过程中每一个元素的别名 |
index | 表示在迭代过程中每次迭代到的位置(下标) |
open | 前缀 |
close | 后缀 |
separator | 分隔符,表示迭代时每个元素之间以什么分隔 |
foreach 通常可以将之用到批量删除、添加等操作中。
<insert id="insertUsers" parameterType="com.xxxx.xxx.demo.entity.User">insert into user (name, age, email)values <foreach collection="list" item="item" separator=",">(#{item.name},#{item.age},#{item.email})</foreach><delete id="deleteUsers" parameterType="integer">delete from userwhere id in<foreach collection="array" item="id" open="(" close=")" separator=",">#{id}</foreach></delete>
sql和include
sql用来定义可重用的 SQL 代码片段,以便在其它语句中使用。 参数可以静态地(在加载的时候)确定下来,并且可以在不同的 include 元素中定义不同的参数值。
include表示引用sql标签,作为sql一部分。
<include refid="sqlvalues"></include>
sql常见的几种用法:
1. 静态写法
<sql id="userCol">id, name, age, email</sql><select id="selectUser" resultMap="BaseResult">select<include refid="userCol"></include>from user</select>
2. 动态加载写法
<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql><select id="selectUsers" resultType="map">select<include refid="userColumns"><property name="alias" value="t1"/></include>,<include refid="userColumns"><property name="alias" value="t2"/></include>from some_table t1cross join some_table t2</select><sql id="sometable">${prefix}Table</sql><sql id="someinclude">from<include refid="${include_target}"/></sql><select id="select" resultType="map">selectfield1, field2, field3<include refid="someinclude"><property name="prefix" value="Some"/><property name="include_target" value="sometable"/></include></select>
动态标签
主要搭配顶级标签使用,实现将映射的 SQL 语句动态化。
if、 where、trim、set、 foreach、choose、bind
if 标签
作用:动态拼接
类似 Java 中的 if 语句,符合判断条件的便执行指定内容,否则跳过判断。
/*
@Param是MyBatis所提供的(org.apache.ibatis.annotations.Param),
作为实体层的注解,作用是用于传递参数,从而可以与SQL中的的字段名相对应
*/List<User> selectUsers(@Param("cjw") Integer id);<select id="selectUsers" parameterType="integer" resultType="com.xxx.xxx.demo.entity.User">select * from user where 1=1<if test="cjw > 10 and cjw != ''">id = #{cjw}</if></select>
where 标签
where标签可以去除多余的 where,作为sql的条件语句。
当使用 if 标签进行动态 SQL 拼接时,如果 if 标签的判断条件不满足的话,便不拼接 if 标签中的内容,这便导致了 SQL 语句的 where 子句缺失,造成 SQL 错误。使用 where 标签便可以解决上述问题,使用 where 标签将 if 标签包裹起来,当 if 标签的判断条件不满足,动态 SQL 不拼接时,便不会向 SQL 语句中插入 where 子句,从而避免该错误。
因为有 where 就必须有查询条件,如果没有便会报错,所以加上 1=1条件。
/*** 使用mybatis的where标签实现查询select数据* @param id* @return*/List<User> selectUsersbyWhere(@Param("cjw") Integer id);
<select id="selectUsersbyWhere" parameterType="integer" resultType="com.xxx.xxx.demo.entity.User">select * from user<where><if test="cjw > 1 and (cjw != '' or cjw != null)">id = #{cjw}</if></where></select>
@Testpublic void selectUsersbyWhere() {userMapper.selectUsersbyWhere(9);}
JDBC Connection [HikariProxyConnection@1201324747 wrapping com.mysql.cj.jdbc.ConnectionImpl@220c9a63] will not be managed by Spring
==> Preparing: select * from user WHERE id = ?
==> Parameters: 9(Integer)
<== Columns: id, name, age, email, creattime, updatetime
<== Row: 9, Sandy, 21, test4@baomidou.com, 2023-01-22 15:36:45, 2023-01-22 15:36:45
<== Total: 1
set标签
用于动态包含需要更新的列,忽略其它不更新的列。该标签会动态地在行首插入 SET 关键字,并会删掉额外的逗号(逗号是使用if标签给列索引赋值时引入的)
/*** 使用mybatis的set标签实现更新update数据* @param user*/void updateUserbyUseSet(User user);
<update id="updateUserbyUseSet" parameterType="com.xxx.xxx.demo.entity.User">update user<set><if test="name !='' and name != null">name = #{name},</if><if test="age !='' and age != null">age = #{age},</if><if test="email !='' and email != null">email = #{email}</if></set>where id = #{id}</update>
@Testpublic void updateUserbyUseSet() {User user = new User();user.setId(14);user.setName("cjw");//这里我们不给他传age,看看set能不能实现动态更新数据
// user.setAge(26);user.setEmail("cjw.163");userMapper.updateUserbyUseSet(user);}
JDBC Connection [HikariProxyConnection@1654228203 wrapping com.mysql.cj.jdbc.ConnectionImpl@7b1e5e55] will not be managed by Spring
==> Preparing: update user SET name = ?, email = ? where id = ?
==> Parameters: cjw(String), cjw.163(String), 14(Integer)
<== Updates: 1
age没传,也就是不更新,mybatis的set标签自动识别需要更新的数据,并去除所带的逗号。
trim标签
trim标签可替代where和set标签,也可以在特定业务场景实现一些功能。
<trim prefix="where | set" prefixOverrides="AND | OR | ,">...</trim>
属性 | 描述 |
---|---|
prefix | 给sql语句拼接的前缀 |
suffix | 给sql语句拼接的后缀 |
prefixOverrides | 去除sql语句前面的关键字或者字符,该关键字或者字符 |
suffixOverrides | 去除sql语句后面的关键字或者字符,该关键字或者字符由suffixOverrides属性指定 |
trim实现where标签
/*** 使用mybatis的trim标签实现where标签的功能进而实现查询select数据* @param id* @param name* @return*/List<User> selectUsers(@Param("cjw") Integer id, String name);
<trim prefix="where" prefixOverrides="and"><if test="cjw > 1 and (cjw != '' or cjw != null)">id = #{cjw}</if><if test="name != null and name != ''">and name = #{name}</if></trim>
PS:cjw是mapper层设置的@Param(“cjw”)有关
@Testpublic void selectUsers() {userMapper.selectUsers(9, "");}
JDBC Connection [HikariProxyConnection@116155384 wrapping com.mysql.cj.jdbc.ConnectionImpl@66223d94] will not be managed by Spring
==> Preparing: select * from user where id = ?
==> Parameters: 9(Integer)
<== Columns: id, name, age, email, creattime, updatetime
<== Row: 9, Sandy, 21, test4@baomidou.com, 2023-01-22 15:36:45, 2023-01-22 15:36:45
<== Total: 1
trim实现set标签
/*** 使用mybatis的trim标签实现set标签的功能进而实现更新update数据* @param user*/void updateUserbyUseTrim(User user);
@Testpublic void updateUserbyUseTrim() {User user = new User();user.setId(13);user.setName("zbd");
// user.setAge(26);user.setEmail("cjw.163");userMapper.updateUserbyUseTrim(user);}
JDBC Connection [HikariProxyConnection@116155384 wrapping com.mysql.cj.jdbc.ConnectionImpl@66223d94] will not be managed by Spring
==> Preparing: update user set name = ?, email = ? where id = ?
==> Parameters: zbd(String), cjw.163(String), 13(Integer)
<== Updates: 1
choose、when、otherwise标签
从多个条件中选择一个(即使多个符合也只执行一个)使用。针对这种情况,MyBatis 提供了 choose标签,类似 Java 的 switch 语句。
/*** mybatis的choose标签实现条件查询select数据* @param user* @return*/List<User> selectUserbyChoose(Userdto user);
<select id="selectUserbyChoose" parameterType="com.xxx.xxx.demo.entity.dto.Userdto" resultType="com.xxx.xxx.demo.entity.User">select * from user<where><choose><when test="age != '' and age != null">age <![CDATA[ <= ]]> #{age}</when><when test="name != '' and name != null">and name like concat('%',#{name},'%')</when><otherwise>and id <![CDATA[ <= ]]> #{id}</otherwise></choose></where></select>
@Testpublic void selectUserbyChoose() {Userdto user = new Userdto();user.setName("c");user.setAge(26);user.setId(10);userMapper.selectUserbyChoose(user);}
JDBC Connection [HikariProxyConnection@1713520020 wrapping com.mysql.cj.jdbc.ConnectionImpl@2bc7db89] will not be managed by Spring
==> Preparing: select * from user WHERE age <= ?
==> Parameters: 26(Integer)
<== Columns: id, name, age, email, creattime, updatetime
<== Row: 7, Jack, 20, test2@baomidou.com, 2023-01-22 15:36:45, 2023-01-22 15:36:45
<== Row: 9, Sandy, 21, test4@baomidou.com, 2023-01-22 15:36:45, 2023-01-22 15:36:45
<== Row: 10, Billie, 24, test5@baomidou.com, 2023-01-22 15:36:45, 2023-01-22 15:36:45
<== Row: 13, zbd, 22, cjw.163, 2023-01-22 17:42:20, 2023-01-24 13:39:46
<== Row: 14, cjw, 22, cjw.163, 2023-01-22 17:42:20, 2023-01-24 13:25:09
<== Total: 5
注意:如果同时符合多个when标签,则穿透执行最后一个符合的when标签,when标签都不符合,则执行otherwise标签;
一般使用choose时,传值较多可采用dto传值的方式。
MyBatis标签实现like模糊查询
/*** mybatis标签实现模糊查询select数据* @param name* @return*/List<User> selectUserlike(String name);
<select id="selectUserlike" resultType="com.先xxx.xxx.demo.entity.User">select * from user<where><if test="name != '' and name != null">name like concat('%',#{userName},'%')</if></where></select>
@Testpublic void selectUserlike() {//查询当前数据库中name中包含c的记录userMapper.selectUserlike("c");}
JDBC Connection [HikariProxyConnection@1276991949 wrapping com.mysql.cj.jdbc.ConnectionImpl@76cf841] will not be managed by Spring
==> Preparing: select * from user WHERE name like concat('%',?,'%')
==> Parameters: c(String)
<== Columns: id, name, age, email, creattime, updatetime
<== Row: 7, Jack, 20, test2@baomidou.com, 2023-01-22 15:36:45, 2023-01-22 15:36:45
<== Row: 14, cjw, 22, cjw.163, 2023-01-22 17:42:20, 2023-01-24 13:25:09
<== Total: 2
MyBatis特殊字符转义
MyBatis在解析XML文件时会将5种特殊字符进行转义,分别是
&, <, >, “, ‘,
当不希望语法被转义时就需要进行特殊处理时,使用
<![CDATA[ 特殊字符写这里边 ]]>
如:小于等于 <![CDATA[ <= ]]>
标签来包含特殊字符,也可以使用XML转义序列来表示特殊字符。
直接写 <= 会报错:
Cause: org.xml.sax.SAXParseException; lineNumber: 117; columnNumber: 22; 元素内容必须由格式正确的字符数据或标记组成。
/*** MyBatis特殊字符转义查询年龄小于等于21的数据记录* @param age* @return*/List<User> selectUserbyage(Integer age);
<select id="selectUserbyage" parameterType="integer" resultType="com.xxx.xxx.demo.entity.User">select * from user<where><if test="age != '' and age != null">age <![CDATA[ <= ]]> #{age}</if></where></select>
@Testpublic void selectUserbyage() {userMapper.selectUserbyage(21);}
JDBC Connection [HikariProxyConnection@1276991949 wrapping com.mysql.cj.jdbc.ConnectionImpl@76cf841] will not be managed by Spring
==> Preparing: select * from user WHERE age <= ?
==> Parameters: 21(Integer)
<== Columns: id, name, age, email, creattime, updatetime
<== Row: 7, Jack, 20, test2@baomidou.com, 2023-01-22 15:36:45, 2023-01-22 15:36:45
<== Row: 9, Sandy, 21, test4@baomidou.com, 2023-01-22 15:36:45, 2023-01-22 15:36:45
<== Total: 2
注意: 在CDATA内部的所有内容都会被解析器忽略,保持原貌。所以在Mybatis配置文件中,要尽量缩小 <![CDATA[ ]]>的作用范围,避免sql标签无法解析的问题。