mybatis的动态sql和代码片段

代码片段

sql标签用于定义SQL片段,可以在其他标签中使用<include/>子标签引用该片段,

    <sql id="sqlid">select * from student</sql>
<select id="selectForeach" resultType="Student">
        <include refid="sqlid" /> where id in
        <foreach collection="list" item="student" open="(" close=")" separator=",">
            #{student.id}
        </foreach>
    </select>

动态sql

动态sql: sql的内容是变化的,可以根据条件获取到不同的sql语句。主要是where部分发生变化
动态sql的实现: 使用的是mybatis提供的标签,<if>,<where>,<foreach>

<if>和<where>

<if>是判断条件的
语法<if test=“判断java对象的属性值”></if>

<!--动态sql,使用if标签,标签中判断为真,将语句加到sql的where后面,
where会自动将if中的多余的and or去掉 -->
    <select id="selectStudentIf" resultType="Student">
        select id,name,age,email from student
        <where>
            <if test="name !=null and name !=''">
                name=#{name}
            </if>
            <if test="age>0">
                or age > #{age}
            </if>
        </where>
    </select>

<foreach>

循环java中的数组,list集合的。主要用在sql语句的in中。
例如
select * from student where id in (1,2,3,4)
public List<Student> selectFor(List<Integetr> idlist)

<!--    foreach标签
collection写参数的类型,数组使用array,如果是List集合使用list
item自定义表示数组和集合成员的变量,要写进括号里的变量
open循环开始时的字符
close循环结束时的字符
separator集合成员之间的分隔符
-->
    <select id="selectForeach" resultType="Student">
        <include refid="sqlid" /> where id in
        <foreach collection="list" item="myid" open="(" close=")" separator=",">
            #{myid}
        </foreach>
    </select>

如果传的是对象,可以访问其属性
括号也可以拼接在外面

<select id="selectForeach" resultType="Student">
	<include refid="sqlid" /> where id in (
		<foreach collection="list" item="student" separator=",">
		#{student.id}
 	</foreach>
 	)
</select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值