Mybatis动态sql用法

Mybatis动态sql分为两种: xml方式和注解方式。

xml

if标签

Test 属性中写的是对象的属性名

<select id="findAll" resultType="Student">

    select * from student where 1= 1

    <if test="and sname!= null ">

        sname= #{sname}
    
    </if>

</select>

Where 标签 可以跟if一起用

<select id="findAll" resultType="Student">
	select * from student 
    <where>
		<if test="and sname!= null ">
			sname= #{sname}
		</if>
    </where>
</select>

 Choose 标签

Otherwise 当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql

<choose>
    <when test = 条件>
        执行的代码
    </when>
    <when test = 条件>
        执行的代码
    </when>
    <otherwise>
    执行的代码
    </otherwise>
</choose>

trim标签  万能标签  可以代替where set

prefix=" "   前面加个什么  

prefixOverrides=" "   前面去个什么

suffixOverrides=" "   最后去个什么

suffix=" "    最后加个什么

<Insert id = xxx  parametertype =xxx > 
insert into student 
	<trim prefix="("  suffixOverrides=","  suffix=")">
		<if test="字段 != null">
			字段,
		</if>
	</trim>
	values
	<trim prefix="(" suffixOverrides="," suffix=")">
		<if test="属性 != null">
			#{属性},
		</if>
    </trim>	
</insert>

foreach标签  一堆相同的数据  可用数组 和 集合两种  

item 存放元素

Collection  存放集合

Index 索引

Open 开头给个什么

Close 结尾给个什么

Separator 分割符 用什么分割元素

数组=array   集合=list

<select id =xxx  resulttype=xxx >
    select * from student where sid in
	<foreach collection="集合/数组" item="名" open=" (" close=")" separator"," >
         #{item名}
	</foreach>
</select>

bind标签 定义一个变量

_parameter 借传进来的值 
<bind name="名" value="_parameter+'%' "/>
select * from student where sname like #{name名}

 

 

        注解方式

  1. 脚本sql
  2. 方法中构建sql
  3. Sql语句构造器

1.脚本形式

//在注解中写<script>标签把动态sql语句抱起来,注意sql语句格式

@Select(“<script> 
    select * from student 
    <where>
    <if test = ssex != null>and sexx = #{}</if>
    </where>
 </script>”)

2.使用方法来构建动态sql语句

需要用到内部类,在内部类定义方法 注:内部类放大的参数和上面的方法参数一致

然后再内部类方法中写sql以及判断,判断不为null的话拼接就OK

@Selectprovider(typr =xxx类名.class  , method“方法名”)
Public xxxx xxxx xxx(ssss);

Class xxx{

    Public String xxxx(ssss){
        String sql = “sql语句”;
        //判断是否为null
        If(){}
        Return sql;
    }
}

3.sql构造器

方法中构建sql比较类似

@Selectprovider(typr =  , method“”)
Public xxxx xxxx xxx(ssss);

Class xxx{

    Public String xxxx(ssss){

    return new SQl(){
        {
            SELECT(“查询字段”)
            FROM(“表名”)
            WHERE(“条件”)
            if判断
        }
    }.toString(); 


    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值