在MyBatis中,可以使用以下动态SQL标签来编写灵活的SQL语句:
一、<if>:条件判断标签,用于在SQL语句中添加条件判断。通过判断给定的条件是否成立,决定是否包含相应的SQL片段。示例:
<select id="getUserList" resultType="User">
SELECT * FROM user
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="email != null">
AND email = #{email}
</if>
</where>
</select>
二、<where>:用于拼接WHERE子句,自动处理WHERE关键字和多个条件之间的连接关系(AND或OR)。示例:
<select id="getUserList" resultType="User">
SELECT * FROM user
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="email != null">
AND email = #{email}
</if>
</where>
</select>
三、<set>:用于拼接UPDATE语句的SET子句,自动处理SET关键字和多个字段更新。示例:
<update id="updateUser" parameterType="User">
UPDATE user
<set>
<if test="username != null">
username = #{username},
</if>
<if test="password != null">
password = #{password},
</if>
<if test="email != null">
email = #{email},
</if>
</set>
WHERE id = #{id}
</update>
四、<trim>:用于自定义SQL语句片段的修剪,可以去除开头或结尾的特定字符。常用于处理动态拼接的SQL语句中的逗号、AND、OR等问题。示例:
<select id="getUserList" resultType="User">
SELECT * FROM user
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="username != null">
AND username = #{username}
</if>
<if test="email != null">
AND email = #{email}
</if>
</trim>
</select>
五、<foreach>:用于遍历集合并拼接对应的SQL语句片段,常用于IN语句的参数拼接。示例:
<select id="getUserListByIds" resultType="User">
SELECT * FROM user
WHERE id IN
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</select>
六、<choose>:类似于Java中的switch语句,根据条件选择执行不同的分支。可以与<when>和<otherwise>配合使用。示例:
<select id="getUserList" resultType="User">
SELECT * FROM user
<where>
<choose>
<when test="username != null">
AND username = #{username}
</when>
<when test="email != null">
AND email = #{email}
</when>
<otherwise>
AND status = 1
</otherwise>
</choose>
</where>
</select>
除了上述提到外,MyBatis还提供了其他一些有用的标签,如:
七、<sql>:定义可重用的SQL片段,在需要的地方可以通过<include>标签引入。示例:
<sql id="userColumns">
username, password, email
</sql>
<select id="getUserList" resultType="User">
SELECT <include refid="userColumns"/> FROM user
</select>
八、<include>:用于引入之前定义的可重用SQL片段。示例:
<select id="getUserList" resultType="User">
SELECT *
FROM user
WHERE id IN
<include refid="userIdList"/>
</select>
<sql id="userIdList">
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</sql>
九、<bind>:用于将一个表达式的结果绑定到一个变量上,便于在后续的SQL语句中使用。示例:
<select id="getUserList" resultType="User">
<bind name="namePattern" value="'%'+username+'%'"/>
SELECT * FROM user
WHERE username LIKE #{namePattern}
</select>
十、<resultMap>:定义查询结果与对象属性之间的映射关系,可以进行高级的结果映射配置。示例:
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id"/>
<result property="username" column="user_name"/>
<result property="email" column="user_email"/>
</resultMap>
<select id="getUserList" resultMap="userResultMap">
SELECT user_id, user_name, user_email
FROM user
</select>
这些是MyBatis中的一些常用动态SQL标签,可以根据具体需求选择合适的标签来编写动态和灵活的SQL语句。使用这些标签可以提高SQL的可读性、可维护性和重用性。