在mybatis中,它提供了一些动态sql标签,可以让程序员更快的进行mybatis的开发,这些动态sql可以通过sql的可重用性。。
常用的动态sql标签:if标签、where标签、sql片段、foreach标签
If标签/where标签
综合查询时,查询条件由用户来输入,用户名称可以为空,需要满足这种情况下的
sql
编写。
Sql片段
Sql片段可以让代码有更高的可重用性
Sql片段需要先定义后使用
Foreach标签
可以循环传入参数值
综合查询时,会根据用户ID集合进行查询
SELECT * FROM USER WHERE id IN (1,2,10)
<?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.itheima.mybatis.mapper.UserMapper">
<!-- 根据用户ID查询用户信息 -->
<select id="findUserById" parameterType="int" resultType="User">
SELECT
* FROM USER WHERE id =#{id}
</select>
<!-- 添加用户 -->
<insert id="insertUser" parameterType="com.itheima.mybatis.po.User">
<selectKey keyProperty="id" resultType="int" order="AFTER">
SELECT
LAST_INSERT_ID()
</selectKey>
INSERT INTO USER
(username,birthday,sex,address)
VALUES(#{username},#{birthday},#{sex},#{address})
</insert>
<!-- 定义sql片段 -->
<!-- sql片段内,可以定义sql语句中任何部分 -->
<!-- sql片段内,最好不用将where和select关键字声明在内 -->
<sql id="whereClause">
<!-- if标签:可以对输入的参数进行判断 -->
<!-- test:指定判断表达式 -->
<if test="user != null">
<if test="user.username != null and user.username != ''">
AND username LIKE '%${user.username}%'
</if>
<if test="user.sex != null and user.sex != ''">
AND sex = #{user.sex}
</if>
</if>
<if test="idList != null">
<!-- AND id IN (#{id},#{id},#{id}) -->
<!-- collection:表示pojo中集合属性的属性名称 -->
<!-- item:为遍历出的结果声明一个变量名称 -->
<!-- open:遍历开始时,需要拼接的字符串 -->
<!-- close:遍历结束时,需要拼接的字符串 -->
<!-- separator:遍历中间需要拼接的连接符 -->
AND id IN
<foreach collection="idList" item="id" open="(" close=")"
separator=",">
#{id}
</foreach>
</if>
</sql>
<!-- 综合查询,查询用户列表 -->
<select id="findUserList" parameterType="com.itheima.mybatis.po.UserQueryVO"
resultType="user">
SELECT * FROM user
<!-- where标签:默认去掉后面第一个AND,如果没有参数,则把自己干掉 -->
<where>
<!-- 引入sql片段 -->
<include refid="whereClause" />
</where>
</select>
<!-- 综合查询用户总数 -->
<select id="findUserCount" parameterType="com.itheima.mybatis.po.UserQueryVO"
resultType="int">
SELECT count(*) FROM user
<!-- where标签:默认去掉后面第一个AND,如果没有参数,则把自己干掉 -->
<where>
<!-- 引入sql片段 -->
<include refid="whereClause" />
</where>
</select>
<!-- resultMap入门 -->
<!-- id标签:专门为查询结果中唯一列映射 -->
<!-- result标签:映射查询结果中的普通列 -->
<resultMap type="user" id="UserRstMap">
<id column="id_" property="id" />
<result column="username_" property="username" />
<result column="sex_" property="sex" />
</resultMap>
<select id="findUserRstMap" parameterType="int" resultMap="UserRstMap">
Select id id_,username username_,sex sex_ from user where id = #{id}
</select>
</mapper>