mybatis 学习记录(3)—— 动态 sql

尊重个人劳动成果,转载请注明出处:
http://blog.csdn.net/czd3355/article/details/71436960

本篇博客主要介绍 mybatis 中动态 SQL 的使用(增删改查)。话不多说,直接进正题了。

1. 动态查询

关键代码:


@Test
public void main() throws Exception {
    StudentDao studentDao = new StudentDao();
    // 输出动态查询结果
    System.out.println(studentDao.findAll(1,null));
    System.out.println(studentDao.findAll(null,"a"));
    System.out.println(studentDao.findAll(1,"czd1"));
}

// 动态查询
public List<Student> findAll(Integer id, String name) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        map.put("id", id);
        map.put("name",name);
        return sqlSession.selectList(nameSpace + ".findAll", map);
    }

小提示 1:在动态 SQL 中,因为 id 的值可能为 null,所以要使用 Integer 类,因为它能够接收 null,如果是 int 接收 null 的话则会报错。

映射文件(studentMapper.xml)

<select id="findAll" parameterType="map" resultType="com.czd.mybatis01.bean.Student">
 SELECT id,`name` FROM stu
    <where>
        <if test="id!=null">
            AND id = #{id}
        </if>
        <if test="name!=null">
            AND `name` = #{name}
        </if>
    </where>
</select>

小提示 2:<if test="id!=null"> 中的 id 是 map 集合的 key 名称,不是 value 值。同理,下面的 name 也是 map 集合的 key 名称。而 AND id = #{id}左边的 id 是表字段名,右边的 id 依然是 map 集合中的 key 名称

小提示 3:另外为什么我的 name 两边要加上 ` ` 呢?因为有时不加的话为报错,所以还是加上比较保险吧,避免不必要的麻烦

输出结果:

这里写图片描述

2. 动态更新

关键代码:

@Test
public void main() throws Exception {
    StudentDao studentDao = new StudentDao();
    // 动态更新
    studentDao.dynaUpdate(16,"aaa");
}

public void dynaUpdate(Integer id, String name) throws Exception {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("id", id);
    map.put("name",name);
    sqlSession.update(nameSpace+".dynaUpdate",map);
    sqlSession.commit();
    sqlSession.close();
}

映射文件(studentMapper.xml)

<update id="dynaUpdate" parameterType="map">
    UPDATE stu
    <set>
        <if test="name!=null">
          `name` = #{name},
        </if>
        <!--
        由于在本例中,只有 idname 字段,所以不能很好地展示动态更新语句。
        假如有多个表字段的话,只要接着写 if 标签就好了,如下。
         <if test="course!=null">
          course = #{course},
        </if>
        -->
    </set>
    WHERE id = #{id}
</update>

小提示 4:第五行最后有一个 , 号,因为 SQL 语句本身就是需要用 , 号连接。比如:UPDATE stu SET name=? ,course = ? where id=?;

同时 set 标签会自动判断哪个是最后一个字段,并去掉最后一个 , 号。在我的例子中,name 就是最后一个字段。

输出结果:

这里写图片描述

3. 动态删除

关键代码:

@Test
public void main() throws Exception {
    StudentDao studentDao = new StudentDao();
    // 动态删除
    studentDao.dynaDelete("22","23","24");
}

 public void dynaDelete(String... ids) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.delete(nameSpace + ".dynaDelete", ids);
        sqlSession.commit();
        sqlSession.close();
}

映射文件(studentMapper.xml)

 <!--
foreach 用于迭代传入过来的参数
    collection 表示传入过来的参数的数据类型。该参数为必选。
        1.如果传入的是单参数且参数类型是一个 List 的时候,collection 属性值为list
        2.如果传入的是单参数且参数类型是一个 array 数组的时候,collection 的属性值为 array
        3.如果传入的参数是多个的时候,我们就需要把它们封装成一个 Map 了,当然单参数也可以封装成 map。
    item 循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。
         具体说明:在list和数组中是其中的对象,在map中是value。
         该参数为必选。
    index 在 list 和数组中,index 是元素的序号,在 map 中,index 是元素的 key
    open 表示该语句以什么开始,
    close 表示该语句以什么结束,
    separator 表示在每次进行迭代之间以什么符号作为分隔符,
-->
<delete id="dynaDelete" >
    DELETE FROM stu WHERE id IN
    <foreach collection="array" open="(" close=")" item="ids" separator=",">
        #{ids}
    </foreach>
</delete>

输出结果:

这里写图片描述

4. 动态插入

关键代码:


@Test
public void main() throws Exception {
    StudentDao studentDao = new StudentDao();
// 动态插入
    Student student1 = new Student();
    student1.setName("test");
    studentDao.dynaInsert(student1);

    Student student2 = new Student();
    studentDao.dynaInsert(student2);
}

public void dynaInsert(Student student) throws Exception {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    sqlSession.update(nameSpace + ".dynaInsert", student);
    sqlSession.commit();
    sqlSession.close();
}

映射文件(studentMapper.xml)

 <!--该 sql 块对应表字段名
    这里的 name 是表字段名
-->
<sql id="key">
    <trim suffixOverrides=",">
        <if test="name!=null">
            `name`
        </if>
    </trim>
</sql>


<!--该 sql 块对应 ?
    这里的 name 是 parameterType 中的对应表字段的 bean 属性名称。
    注:本例中的 bean 属性名和表字段刚好重名
 -->
<sql id="value">
    <trim suffixOverrides=",">
        <if test="name!=null">
            #{name}
        </if>
    </trim>
</sql>

<delete id="dynaInsert" parameterType="com.czd.mybatis01.bean.Student">
    INSERT INTO stu (<include refid="key"/>)VALUES (<include refid="value"/>)
</delete>

输出结果:

这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值