mybatis 常用标签

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="mapper接口全限定名">

</mapper>

if

<!-- 字符串 -->
<if test = "studentName != null and studentName !='' ">     
     
</if> 
<!-- 集合 -->
<if test = "idList != null and idList.size() > 0 ">     
     
</if> 

foreach

<delete id="deleteBatch"> 
	delete from user where id in
	<foreach collection="idList" item="id" index="index" open="(" close=")" separator=",">
  		#{id}
	</foreach>
</delete>

where

<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
SELECT * from t_user    
<where>
    <!-- mybatis 会优化,第一个and会被去掉,所以当多个条件时第一个 and 要不要都可以 -->
    <if test="studentName!=null and studentName!='' ">     
   		AND name LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
    </if>     
    <if test="studentSex!= null and studentSex!= '' ">     
    	AND sex = #{studentSex}      
    </if>   
</where> 
</select>

choose

<select id="selectUserByStatus" parameterType="String" resultType="User">
    SELECT * FROM users
    <where>
        <choose>
            <!-- 当传入的状态为 'active' 时,选择此条件 -->
            <when test="status == 'active'">
                and is_active = 1
            </when>
            <!-- 当传入的状态为 'inactive' 时,选择此条件 -->
            <when test="status == 'inactive'">
                and is_active = 0
            </when>
            <!-- 如果没有匹配的 <when> 条件,则执行 <otherwise> 中的内容 -->
            <otherwise>
                and id = -1  <!-- 假设不可能有ID为-1的用户 -->
            </otherwise>
        </choose>
    </where>
</select>

include

<?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="mapper接口全限定名">
    <!-- 定义标签 -->
    <sql id="sql_count">
            select count(*)
    </sql>
    <sql id="sql_select">
            select *
    </sql>
    
    <!-- 使用标签 -->
    <select id="selectCount" resultType="com.iot.site.module.quote.entity.Quote">
    	<include refid = "sql_count"/> from site_quote
	</select>
</mapper>
posted @ 2024-04-29 11:04  黄光跃  阅读(2)  评论(0编辑  收藏  举报