动态MyBatis标签详解 - 极悦
专注Java教育14年 全国咨询/投诉热线:444-1124-454
极悦LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 动态MyBatis标签详解

动态MyBatis标签详解

更新时间:2022-04-15 08:41:51 来源:极悦 浏览2132次

MyBatis标签是大家需要了解的,极悦小编来为大家介绍一下MyBatis的动态标签。

if label

if label test属性中有一个,test属性值是匹配OGNL必选判断表达式,表达式的结果可以使true或者false,另外,所有非0的值都为true

1.数值型

(1)for example :

If there is no special requirement when the parameter is numeric, you only need to judge whether it is null that will do .
<if test="id != null"></if>

(2)for example :

If there is a special demand , For example, judge whether it is greater than a certain number . Just add the corresponding conditional judgment .
<if test='id != null and id > 28'></if>

(3)for example :

mybatis There is another form for this greater than less than and so on .
<if test='id != null and id gt 28'></if>
<if test='id != null and id > 28'></if>  The two are the same 
<if test='id != null and id gte 28'></if>
<if test='id != null and id >= 28'></if>  The two are the same 
<if test='id != null and id lt 28'></if>  normal 
<if test='id != null and id < 28'></if>  Report errors 
<if test='id != null and id lte 28'></if>  normal 
<if test='id != null and id <= 28'></if>  Report errors 

对应关系:

gt           Corresponding              >
gte          Corresponding               >=
lt            Corresponding              <( Will report a mistake    The associated  "test"  Property values cannot contain  '<'  character )
lte           Corresponding              <=( Will report a mistake    The associated  "test"  Property values cannot contain  '<='  character )

 2.字符串类型

(1)for example :

If you do not need to filter empty strings   Just judge null that will do 
<if test="username != null"></if>

(2)for example :

If you need to filter empty strings , Add an empty string to judge    I won't support it  && and  || , So here we use  and  or  To make logical and or judgments  
<if test="username != null and '' != username"></if>  perhaps  <if test="username != null and '' neq username"></if>

(3)for example :

If you judge whether the string starts with a special character , Ending, etc . Call directly String The corresponding method can be used 
    <if test="username != null and username.indexOf('ji') == 0"> </if> <!--  Whether it starts with something  -->
    <if test="username != null and username.indexOf('ji') >= 0"> </if> <!--  Whether it contains a character  -->
    <if test="username != null and username.lastIndexOf('ji') > 0"></if>  <!--  Does it end with something  -->

(4)for example :

Whether it is a specific string , Some businesses need this .
<if test="username != null and 'hello' == username"></if>  perhaps <if test="username != null and 'hello' eq username"></if>
 Be careful :
     <if test="username != null and 'hello' == username"></if> There is no problem with this form of writing when the parameter type is a string ,
 However, when the parameter type is non string type, it needs to be written as  <if test="username != null and 'hello'.toString() == username.toString()"></if>
 Just write <if test="username != null and 'hello'.toString() == username"></if> There will also be a great possibility of hanging up .
 Maybe you will say why non string should be written like this . This depends on the special needs .

对应关系:

eq                   Corresponding                 ==
neq                Corresponding                  !=
 3  Judge list Is it empty 
if Condition judgment can directly call the method of the object itself for logical judgment , therefore list Sentenced to empty . You can call .size()>0 perhaps .isEmpty()
 for example :<if test="userList != null and userList.isNotEmpty()"></if> , <if test="userList != null and userList.size()>0"></if>
4 map Parameters are the same    If the value is taken  map.key(map Medium key name ) that will do

where label

标签会自动判断,如果没有条件成立,那么在sql中就不会有...语句中 where关键字

如果有任何条件成立,会自动去掉多余的或者or。(我们不需要添加 1=1 这样的侵入代码)

usage :

<select id="listProduct" resultType="Product">
    select * from product_
    <where>
        <if test="name!=null">
            and name like concat('%',#{
    name},'%')
        </if>        
        <if test="price!=null">
            and price > #{
    price}
        </if>
    </where>     
</select>

set label

和 where Labels 类似,在 update 语句中也会出现多个字段相关的问题。在这种情况下,您可以使用 set label 。它的作用和 where 标签相似,只有在有数据时才设置。set 元素可用于动态包含需要更新的列,忽略其他不更新的列,set 元素在行首动态插入 SET 关键字,并删除多余的逗号。

usage :

<update id="updateProduct" parameterType="Product" >
    update product_
    <set>
        <if test="name != null">name=#{
    name},</if>
        <if test="price != null">price=#{
    price}</if> 
    </set>
     where id=#{
    id}   
</update>

trim 标签

trim 有四个参数,即:

prefix: Prefix(以什么开头)、

prefixoverride: 去掉第一个(如“and”还是“or”)

suffix: suffix(以什么结尾)

suffixoverride:去掉最后一个标记的字符(如“,”)

usage :

<select id="listProduct" resultType="Product">
    select *from product_
    <trim prefix="WHERE" prefixOverrides="AND |OR ">
        <if test="name!=null">
            and name like concat('%',#{
    name},'%')
        </if>        
        <if test="price!=null and price!=0">
            and price > #{
    price}
        </if>
    </trim>      
</select>
trim  Used to customize the desired functions , such as where The label can be used trim  To replace 
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ... 
</trim>  
<update id="updateProduct" parameterType="Product" >
    update product_
    <trim prefix="SET" suffixOverrides=",">
        <if test="name != null">name=#{
    name},</if>
        <if test="price != null">price=#{
    price},</if>   
    </trim>
     where id=#{
    id}   
</update>
set The label can be used trim To replace  , function set The code in the tag , The effect is the same .
<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

choose when else label

有时候我们不想套用所有的条件,我只想选择几个选项中的一个。MyBatis 提供了选择元素,按顺序判断 when 中的条件是否为真,如果一个成立,则为选择结束。当您在何时选择所有条件时,如果您对所有条件不满意,则执行其他媒体SQL。类似于 Java 的 switch 语句,按 switch 选择,when 按大小写,否则为 default.if 是与 (and) 之间的关系,并且选择 Yes 或 (or) 之间的关系.

<select id="getUserList" resultType="com.it.bean.User" parameterType="com.it.bean.User">  
    SELECT <include refid="resultParam"></include> FROM User u   
    <where>  
        <choose>  
            <when test="username !=null and username != ''">  
                u.username LIKE CONCAT(CONCAT('%', #{
    username}),'%')  
            </when >  
            <when test="sex != null">  
                AND u.sex = #{
    sex}  
            </when >  
            <when test="birthday != null ">  
                AND u.birthday = #{
    birthday}  
            </when >  
            <otherwise> 
 	            AND u.age = #{
    age}
            </otherwise>  
        </choose>  
    </where>    
</select>

foreach 标签

foreach 标签通常用于在这种语法中。

collection :collection 一个属性有三个取值 list、array、map 三个,对应的参数类型有:List、 Array 、map aggregate ,我上面传的参数是array ,所以取值为array

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

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

open : 前缀

关闭:后缀

separator : 分隔符,表示迭代过程中每个元素是如何分隔的.

<select id="listProduct" resultType="Product">
      SELECT * FROM product_
        WHERE ID in
            <foreach item="item" index="index" collection="list"
                open="(" separator="," close=")">
                #{
    item}
            </foreach>
</select>

bind label

bind在label中,value对应传入实体类的一个字段,name属性是赋予对应字段的变量名。在 value 属性中可以使用字符串拼接等特殊处理。

usage :

    <select id="listProduct" resultType="Product">
        <bind name="likename" value="'%' + name + '%'" />
        select * from   product_  where name like #{
    likename}
    </select>

sql Fragment tags

通过这个标签,我们可以定义可复用的 sql 语句片段,在执行的 sql 语句标签中可以直接引用。

这样可以提高编码效率,也可以有效地简化代码,提高可读性。sql label 封装SQL语言,包括要调用的Tag。

usage :

<!-- Definition sql fragment -->
<sql id="orderAndItem">    o.order_id,o.cid,o.address,o.create_date,o.orderitem_id,i.orderitem_id,i.product_id,i.count
</sql>
<select id="findOrderAndItemsByOid" parameterType="java.lang.String" resultMap="BaseResultMap">
    select
<!-- quote sql fragment -->
    <include refid="orderAndItem" />
    from ordertable o
    join orderitem i on o.orderitem_id = i.orderitem_id
    where o.order_id = #{
    orderId}
</select>

 

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>