mybatis学习笔记(5) ---- 动态Sql

mybatis学习笔记(5) ---- 动态Sql

mybatis中的一大特性就是动态sql,在传统的JDBC编程中,根据条件编写,拼接SQL语句很容易出错,因此mybatis引入了动态sql。动态Sql元素和JSTL(jSP标准标签库)很像。动态sql的本质就是对sql进行灵活拼接和组装。

if标签

if标签最常用到,在查询和删除更新数据的时候作判断时结合test属性使用。主要用来判断参数是否合法,如参数不能为null等。

mapper.xml
<select id="find" parameterType="com.excellent.po.User" resultType="com.excellent.po.User">
        select * from user
        <where>
            <if test="user != null">
                <if test="user.id != null">
                    AND id &gt; #{user.id}
                </if>
                <if test="user.sex != null">
                    AND sex = #{user.sex}
                </if>
            </if>
        </where>
    </select>
test
 @Test
    public void test6(){
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setId(10);
        user.setSex("1");
        List<User> list = mapper.find(user);
        for(User user1 : list){
            System.out.println(user1);
        }
        sqlSession.close();

    }

foreach标签

顾名思义,这个标签是用来循环遍历的,可以实现多个相同样式条件的查询。

mapper.xml
<select id="findById" parameterType="java.util.ArrayList" resultType="java.util.Map">

        <!--
            select * from user where id in (1,10,16,22)
            collection:指定输入 对象中集合属性
            item:每个遍历生成对象中
            open:开始遍历时拼接的串
            close:结束遍历时拼接的串
            separator:遍历的两个对象中需要拼接的串
        -->

        SELECT *
        FROM user
        WHERE id in
        <foreach item="i"  collection="list" open="("
                 separator="," close=")">
            #{i}
        </foreach>

    </select>
set标签
  • mapper.xml
<mapper namespace="com.excellent.mapper.UserMapper">
    <insert id="adduser" parameterType="com.excellent.po.User">
        update user
        <set>
            <if test="user.sex != null">
                 sex = #{user.sex}
            </if>
            <if test="user.username != null">
                and username = #{user.username}
            </if>
        </set>
                where id = #{user.id}
    </insert>

Sql片段

将一些常用的,出现几率高的sql语句抽出来,用sql标签封装起来,就像一个函数一样,用的时候,只需要调用即可,无需重写。减少代码冗余。

  • mapper.xml
 <sql id="mysql1">
        select * from user
    </sql>

 <select id="findAll" resultType="com.excellent.po.User">
        <include refid="mysql1"/>
  </select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值