java mybatis总结--标签

时间:2025-08-27 09:54:02来源:互联网

下面小编就为大家分享一篇java mybatis总结--标签,具有很好的参考价值,希望对大家有所帮助。

标签种类

标签说明

select 标签 

属性介绍:

id :唯一的标识符。

parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User或user。

resultType :语句返回值类型或别名。注意,如果是集合,那么这里填写的是集合的泛型,而不是集合本身(resultType 与resultMap 不能并用)

<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">

        select * from student where id=#{id}

</select>

insert标签

属性介绍:

id :唯一的标识符

parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User

<insert id="insert" parameterType="Object">
        insert into student    
<trim     prefix="("    suffix=")"    suffixOverrides="," >    
    <if test="name != null  "> NAME,  </if>    
</trim>    
<trim     prefix="values("    suffix=")"    suffixOverrides="," >
    <if test="name != null  ">  #{name},  </if>    
</trim>
</insert>

delete标签

属性介绍:

id :唯一的标识符

parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User

<delete id="deleteByPrimaryKey" parameterType="Object">
        delete      from student where id=#{id}
</delete>

update标签

属性介绍:

id :唯一的标识符

parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User

<!--update 标签-->
<update id="updateWebsite" parameterType="string">
    update website set name = #{name}
</update>

resultMap 标签

建立SQL查询结果字段与实体属性的映射关系信息,注意:与java对象对应的列不是数据库中表的列名,而是查询后结果集的列名

<resultMap id="BaseResultMap" type="com.online.charge.platform.student.model.Student">
    <id property="id" column="id" />
    <result column="NAME" property="name" />
    <result column="HOBBY" property="hobby" />
    <result column="MAJOR" property="major" />
    <result column="BIRTHDAY" property="birthday" />
    <result column="AGE" property="age" />
</resultMap>
<!--查询时resultMap引用该resultMap -->  
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
  select id,name,hobby,major,birthday,age from student where id=#{id}
</select>

 

主标签:

id:该resultMap的标志

type:返回值的类名,此例中返回Studnet类

子标签:

id:用于设置主键字段与领域模型属性的映射关系,此处主键为ID,对应id。

result:用于设置普通字段与领域模型属性的映射关系

 if 标签

if标签通常用于WHERE语句、UPDATE语句、INSERT语句中,通过判断参数值来决定是否使用某个查询条件、判断是否更新某一个字段、判断是否插入某个字段的值。

<if test="name != null and name != ''">
         and NAME = #{name}
</if>

1.判断条件property!=null或者property==null:适用于任何类型的字段,用于判断属性值是否为空

2.判断条件property!=''或者property=='':仅适用于String类型的字段,用于判断是否为空字符串

 

如果为字符串类型

如果不需要过滤空串的情况 仅仅判断null即可

例如:<if test="username != null"></if>

如果需要过滤空串,添加空串判断即可不支持 &&所以这里用 and  or  || 来做逻辑与或的判断 

例如:<if test="username != null and '' != username"></if> 或者 <if test="username != null and ''  neq username"></if>

如果判断字符串是否已某个特俗字符开头,结尾等。直接调用String的对应方法即可

例如:<if test="username != null and username.indexOf('ji') == 0"> </if> <!-- 是否以什么开头 -->

    <if test="username != null and username.indexOf('ji') >= 0"> </if> <!-- 是否包含某字符 -->

    <if test="username != null and username.lastIndexOf('ji') > 0"></if>  <!-- 是否以什么结尾 -->

是否是某个特定字符串,某些业务有此需要。

例如:<if test="username != null and 'hello' == username"></if> 或者<if test="username != null and 'hello' eq username"></if>(eq 对应==,neq 对应!=)

注意:

<if test="username != null and 'hello' == username"></if>这种形式的写法在参数类型是字符串的时候是没有问题的,但是参数类型为非字符串类型的时候就需要写成 <if test="username != null and 'hello'.toString() == username.toString()"></if>

 

判断list是否为空

if条件判断可以直接调用对象自身的方法进行逻辑判断,所以list判空。可以调用.size()>0或者.isEmpty()

例如:<if test="userList != null and userList.isEmpty()"></if> , <if test="userList != null and userList.size()>0"></if>

 

 数字类型

仅作null判断。<if test='id != null'>

大小判断<if test='id != null and id lt 28 '>

gt 对应>  gte对应>=   lt对应<  lte对应<=

<(会报错  相关联的 "test" 属性值不能包含 '<' 字符)

<=(会报错  相关联的 "test" 属性值不能包含 '<' 字符)

 

时间类型

仅作null判断

<if test="record.updateTime != null">

        update_time = #{record.updateTime,jdbcType=TIMESTAMP},

      </if>

foreach 标签

foreach标签主要用于构建in条件,可在sql中对集合进行迭代。也常用到批量删除、添加等操作中。

<!-- in查询所有,不分页 -->
<select id="selectIn" resultMap="BaseResultMap">
    select name,hobby from student where id in
    <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
        #{item}
    </foreach>
</select>

属性介绍:

 

collection:collection属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合。可以在mapper文件中使用@Param注解指定名称,

item :表示在迭代过程中每一个元素的别名

index :表示在迭代过程中每次迭代到的位置(下标)

open :前缀

close :后缀

separator :分隔符,表示迭代时每个元素之间以什么分隔

 

choose标签

有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis提供了choose 元素,按顺序判断when中的条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行 otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。

 

 if是与(and)的关系,而choose是或(or)的关系

<select id="getStudentListChoose" parameterType="Student" resultMap="BaseResultMap">     
    SELECT * from STUDENT WHERE 1=1    
    <where>     
        <choose>     
            <when test="Name!=null and student!='' ">     
                   AND name LIKE CONCAT(CONCAT('%', #{student}),'%')      
            </when>     
            <when test="hobby!= null and hobby!= '' ">     
                    AND hobby = #{hobby}      
            </when>                   
            <otherwise>     
                    AND AGE = 15  
           </otherwise>     
        </choose>     
    </where>     
</select>  

 

where标签

这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

<select id="getStudentListWhere" parameterType="Object" resultMap="BaseResultMap">     
    SELECT * from STUDENT      
       <where>   
         <if test="name!=null and name!='' ">     
            NAME LIKE CONCAT(CONCAT('%', #{name}),'%')      
         </if>     
         <if test="hobby!= null and hobby!= '' ">     
            AND hobby = #{hobby}      
         </if>  
       </where>        
</select>

 

set标签

使用set标签可以将动态的配置set关键字,和剔除追加到条件末尾的任何不相关的逗号。

<update id="updateStudent" parameterType="Object">     
    UPDATE STUDENT      
    <set>     
        <if test="name!=null and name!='' ">     
            NAME = #{name},      
        </if>     
        <if test="hobby!=null and hobby!='' ">     
            MAJOR = #{major},      
        </if>
        <if test="hobby!=null and hobby!='' ">     
            HOBBY = #{hobby}    
        </if>     
    </set>     
    WHERE ID = #{id};      
</update>  

 trim标签

trim标记是一个格式化的标记,主要用于拼接sql的条件语句(前缀或后缀的添加或忽略),可以完成set或者是where标记的功能。

trim属性主要有以下四个

 prefix:前缀覆盖并增加其内容

 suffix:后缀覆盖并增加其内容

 prefixOverrides:前缀判断的条件

 suffixOverrides:后缀判断的条件

<update id="updateByPrimaryKey" parameterType="Object">
        update student set
  <trim  suffixOverrides="," >
    <if test="name != null  ">
        NAME=#{name},
    </if>
    <if test="hobby != null  ">
        HOBBY=#{hobby},
    </if>
  </trim> where id=#{id}
    </update>

如果name和hobby的值都不为空的话,会执行如下语句

update student set NAME='XX',HOBBY='XX' /*,*/ where id='XX'

会忽略最后一个“,” ;

<select id="selectByNameOrHobby" resultMap="BaseResultMap">
select * from student
<trim prefix="WHERE" prefixOverrides="AND | OR">
    <if test="name != null and name.length()>0"> 
            AND name=#{name}
    </if>
    <if test="hobby != null and hobby.length()>0"> 
            AND hobby=#{hobby}
    </if>
</trim>
</select>

如果name和hobby的值都不为空的话,会执行如下语句

select * from user WHERE /*and*/ name = ‘xx’ and hobby= ‘xx’

会为<trim>片段添加 "WHERE" 前缀,并忽略第一个 “and”  ;

当然,避免出现“WHERE AND”还有其他方法,如下

<!--将where提取出来,并加上“1=1”的查询条件 -->
select * from student
where 1=1
<trim suffixOverrides=",">
   <if test="name != null and name != ''">
      and NAME = #{name}
   </if>
   <if test="hobby != null and hobby != ''">
      and HOBBY = #{hobby}
   </if>
</trim>

用在insert中

<insert id="insert" parameterType="Object">
        insert into student    <trim     prefix="("    suffix=")"    suffixOverrides="," >
    <if test="name != null  ">
       NAME,
    </if>
    <if test="hobby != null  ">
        HOBBY,
    </if>    
    </trim>    
    <trim     prefix="values("    suffix=")"    suffixOverrides="," >  
    <if test="name != null  ">
        #{name},
    </if>
    <if test="hobby != null  ">
        #{hobby},
    </if>
  </trim>
</insert>

 

collection标签和association标签

association标签:

用于一对一查询

属性property,用于指定实体类中的属性名称如user表有dept属性,这里就填dept

属性column,数据库的列名或者列标签别名。

属性jdbcType,结果的数据类型

属性resultMap,可以定义resultMap进行接收数据

collectio用于一对多查询,

<resultMap id="userMap" type="com.air.manager.pojo.agent.User">
        <id column="USER_ID" property="user_id" jdbcType="VARCHAR" />
        <result column="USER_NAME" property="user_name" jdbcType="VARCHAR" />

        // 一、关联单个对象 association ,如果关联对象超过一个会报错  
        //方法1 使用select属性查找selectRecordByUserId去加载
        <association property="record" column="USER_ID" select="selectRecordByUserId"/>


        //方法2 直接在内部定义record属性
        <association property="record" javaType="com.air.manager.pojo.agent.Record" >
            <id column="RECORD_ID" property="record_id" jdbcType="VARCHAR" />
            <result column="RECORD_NAME" property="record_name" jdbcType="VARCHAR" />
        </association >
        // 二、关联对象集合 collection
        //方法1 使用select属性查找selectRecordByUserId去加载
        <collection property="recordList" column="USER_ID" select="selectRecordByUserId"/>

        //方法2 直接在内部定义recordList集合 ,javaType="java.util.ArrayList"可以不添加
        <collection property="recordList" ofType="com.air.manager.pojo.agent.Record"  javaType="java.util.ArrayList" >
            <id column="RECORD_ID" property="record_id" jdbcType="VARCHAR" />
            <result column="RECORD_NAME" property="record_name" jdbcType="VARCHAR" />
        </collection>
</resultMap>
<resultMap id="recordMap" type="com.air.manager.pojo.agent.Record">
        <id column="RECORD_ID" property="record_id" jdbcType="VARCHAR" />
        <result column="RECORD_NAME" property="record_name" jdbcType="VARCHAR" />
</resultMap>


<select id="selectRecordByUserId" resultMap="recordMap">
        SELECT  
         R.RECORD_ID,
         R.RECORD_NAME
        FROM KING_RECORD R WHERE R.USER_ID=#{userId} //这里的userId名称可以随意,一样可以取到值
</select>

 

 

sql标签

当多种类型的查询语句的查询字段或者查询条件相同时,可以将其定义为常量,方便调用。为求<select>结构清晰也可将sql语句分解。

<!-- 查询字段 -->
    <sql id="Base_Column_List">
        ID,MAJOR,BIRTHDAY,AGE,NAME,HOBBY
    </sql>

 <!-- 查询条件 -->

    <sql id="Example_Where_Clause">
        where 1=1
        <trim suffixOverrides=",">
            <if test="id != null and id !=''">
                and id = #{id}
            </if>

            <if test="major != null and major != ''">
                and MAJOR = #{major}
            </if>

            <if test="birthday != null ">
                and BIRTHDAY = #{birthday}
            </if>
            <if test="age != null ">
                and AGE = #{age}
            </if>
            <if test="name != null and name != ''">
                and NAME = #{name}
            </if>
            <if test="hobby != null and hobby != ''">
                and HOBBY = #{hobby}
            </if>            
            <if test="sorting != null">
                order by #{sorting}
            </if>
            <if test="sort!= null  and sort != '' ">
                order by ${sort}   ${order}
            </if>
        </trim>
    </sql>

include标签

用于引用定义的常量

<!-- 查询所有,不分页 -->
    <select id="selectAll" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM
        student
        <include refid="Example_Where_Clause" />
    </select>

<!-- 分页查询 -->
    <select id="select" resultMap="BaseResultMap">
        select * from (
            select tt.*,rownum as rowno from
                (
                    SELECT
                    <include refid="Base_Column_List" />
                    FROM
                    student
                    <include refid="Example_Where_Clause" />
                     ) tt
                     <where>
                            <if test="pageNum != null and rows != null">
                            and  rownum  <![CDATA[<=]]>#{page}*#{rows}
                         </if>
                    </where>
             ) table_alias
            where table_alias.rowno>#{pageNum}

    </select>
<!-- 根据条件删除 -->
    <delete id="deleteByEntity" parameterType="java.util.Map">
    DELETE  FROM   student
    <include refid="Example_Where_Clause" />
    </delete>

bind标签

每个数据库的拼接函数或连接符号都不同,例如 MySQL 的 concat 函数、Oracle 的连接符号“||”等。这样 SQL 映射文件就需要根据不同的数据库提供不同的实现,显然比较麻烦,且不利于代码的移植。幸运的是,MyBatis 提供了 bind 标签来解决这一问题。

bind 标签可以通过 OGNL 表达式自定义一个上下文变量。

<select id="selectWebsite" resultType="net.biancheng.po.Website">
    <bind name="pattern" value="'%'+_parameter+'%'" />
    SELECT id,name,url,age,country
    FROM website
    WHERE name like #{pattern}
</select>

bind 元素属性如下。
value:对应传入实体类的某个字段,可以进行字符串拼接等特殊处理。
name:给对应参数取的别名。

以上代码中的“_parameter”代表传递进来的参数,它和通配符连接后,赋给了 pattern,然后就可以在 select 语句中使用这个变量进行模糊查询

参数是一个多属性引用类型时:

public List<Website> selectWebsite(Website site);

<select id="selectWebsite" resultType="net.biancheng.po.Website">
    <bind name="pattern_name" value="'%'+name+'%'" />
    <bind name="pattern_url" value="'%'+url+'%'" />
    SELECT id,name,url,age,country
    FROM website
    WHERE name like #{pattern_name}
    AND url like #{pattern_url}
</select>

 

参数为多个引用类型时:

List<BillSummaryDayVO> billSummary(@Param("tables") List<String> tables, @Param("dto") BillDetailSummaryQueryDTO dto);

<select id="billSummary" resultType="com.ctfo.pay.model.vo.BillSummaryDayVO">
 <if test="null != dto.plateNumber and '' != dto.plateNumber">
 <bind name="plateLike" value="'%'+ dto.plateNumber + '%'" />
 </if>
 <foreach collection="tables" item="table" open="" separator=" UNION ALL " close="">
 SELECT
        sum(third_real_amount) txAmount,
        count(bill_detail_id) txCount,
        sum(case when bill_type = 2 then third_real_amount else 0 end) refundAmount ,
        count(case when bill_type = 2 then bill_detail_id end) refundCount,
        sum(case when bill_type = 1 then third_real_amount else 0 end) amount,
        count(case when bill_type = 1 then bill_detail_id  end) count,
        sum(channel_fee) serviceCharge
        from ${table}
        WHERE
        status=1
        AND third_total_amount != 0
        <if test="null != dto.billDateStart and '' != dto.billDateStart">
 AND bill_date &gt;= #{dto.billDateStart}
        </if>
 <if test="null != dto.billDateEnd and '' != dto.billDateEnd">
 AND bill_date &lt;= #{dto.billDateEnd}
        </if>
 <if test="null != dto.accessMode">
 AND access_mode = #{dto.accessMode}
        </if>
 <if test="null != dto.businessId and '' != dto.businessId">
 AND business_id = #{dto.businessId}
        </if>
 <if test="null != dto.bizTypeCode and '' != dto.bizTypeCode">
 AND biz_type_code = #{dto.bizTypeCode}
        </if>
 <if test="null != dto.channelType ">
 AND channel_type = #{dto.channelType}
        </if>
 <if test="null != dto.plateNumber and '' != dto.plateNumber">
 AND plate_nums like #{plateLike}
        </if>
 <if test="null != dto.storeIds and dto.storeIds.size() > 0">
 AND store_id in
            <foreach collection="dto.storeIds" item="id" open="(" separator="," close=")">
 #{id}
            </foreach>
 </if>
 <if test="null != dto.organIds and dto.organIds.size() > 0">
 AND organ_id in
            <foreach collection="dto.organIds" item="id" open="(" separator="," close=")">
 #{id}
            </foreach>
 </if>
 </foreach>
</select>

用@Param指定的名称获取属性值就行

本站部分内容转载自互联网,如果有网站内容侵犯了您的权益,可直接联系我们删除,感谢支持!