myBatis数据库常用标签

时间:2023-03-09 04:30:37
myBatis数据库常用标签

<sql id=””></sql>:封装sql语句,被其他sql调用

<include refid=””></include>:调用封装sql

<if test=” title_name != null”>AND title_name =#{titleName}</if>:判断标签,

<choose></choose>:相当于java中的switch语句。当when条件满足时,输出when条件中的语句,可以有多个when语句。当when条件不满足时,输出otherwise中的语句,myBatis会自动忽略首个and或or,where1=1当条件都等于null是查全表

select * from from_name where 1=1

<choose>

<when test=” title_name != null”>

AND title_name =#{titleName}

</when>

<otherwise>

AND title_name =#{titleName}

</otherwise>

</choose>

<set></set>:主要用于更新操作,作用是在包含的语句前输出第一个set,如果包含的语句是以逗号结尾的,会忽略该逗号,如果set的内容为空,会报错,使用set可以动态的更新sql

update from_name

<set>

<if test=”title != null”> title = #{title},</if>

<if test = “content != null”> content = #{content},</if>

<if test= “name != null AND name != ‘’ ”>name=#{name}</if>

</set>

where id=#{id}

<trim></trim>:在自己包含的内容前加上前缀或后缀,与之对应的属性是prefix和suffix,可以把包含内容的首部某些内容覆盖既忽略,也可以把尾部某些内容覆盖,与之对应的属性是prefixOverrides和suffixOverrides,通常使用trim代替where

select * from from_name

<trim prefix=”where”prefixOverrides=”and | or”>

<if test = “title != null”>AND title=#{title}</if>>

<if test= “name != null”>AND name=#{name}</if>

</trim>

<foreach></foreach>:循环,它可以在sql中进行迭代一个集合,主要属性:

item:表示集合每次迭代时属性的别名,在list和数组中是对象,在map中是value。该参数是必须的

collection:集合用array代替为主键

list<?>对象默认用list代替为主键

map对象用map代替为主键

当参数为某个对象的字段时:

如果User有属性List ids。入参是User对象,那么这个collection = "ids"

如果User有属性Ids
ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection
= "ids.id"。该参数是必须的

open:代码开始符,一般和close一起合用open=”(” close=”)”可选

close:代码关闭符,一般和close一起合用open=”(” close=”)”可选

separator:元素之间的分割符,例如在in()时,separato=”,”会自动在元素中间使用“,”隔开,避免手动输入sql错误。该参数可选

index:在list和数组中是元素的序号,在map中是key。该参数可选

删除例子

delete from
from_name id in

<foreach item
=“id”collection=”array”open=”(” separator = “,” close = “)”>

#{id}

</foreach>