zoukankan      html  css  js  c++  java
  • mybatis处理集合、循环、数组和in查询等语句的使用

    在Mybatis的xml配置中使用集合,主要是用到了foreach动态语句。

    foreach的参数:
    foreach元素的属性主要有 item,index,collection,open,separator,close。
    item表示集合中每一个元素进行迭代时的别名.
    index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置.
    open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符.
    close表示以什么结束。

    1. Mybatis生成select * from table where id in(1,2,...,n)语句的查询

    我们一般的做法是在方法的参数处指定传入的参数名称,在xml中使用的时候,集合的名称要和方法的Param的名称一致,这样便于阅读和理解,然后是在对应的xml文件中使用foreach循环。

    java代码如下:

    public abstract List<Model> findByIds(@Param("ids")List<Integer> ids);

    对应的xml代码如下:

    select * from table
    <where>
        id in <foreach collection="ids" item="item" index="index" 
    open="(" separator="," close=")">#{item}</foreach>
    </where>

    2.Mybatis保存多条记录

    我们同样是通过foreach的方法来实现,这里我们巧妙的利用了sql的语法规则用Mybatis的foreach动态语句来处理。

    java代码:

    public abstract void saves(@Param("tables")List<Model> tables);

    xml代码:

    insert into table(name,addtime) values
    <foreach collection="tables" item="item" index="index" separator=",">  
        (#{item.name},#{item.addtime})
    </foreach>

    以上方法Mybatis会帮我们进行sql注入拦截,Mybatis如果采用#{xxx}的形式设置参数,Mybatis会进行sql注入的过滤。如果采用的是${xxx},Mybatis不会进行sql注入过滤,而是直接将参入的内容输出为sql语句。

    判断集合是否有值

    <if test="list!=null and list.size()>0"></if>
  • 相关阅读:
    (Power Strings)sdutoj2475
    KMP(http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2772)
    spfa 判断负环 (转载)
    图的存储
    图结构练习——判断给定图是否存在合法拓扑序列(sdutoj)
    poj1753Flip Game(dfs)
    poj2524(简单并查集)
    VC++ GetModuleFileName()获取路径字符串中带波浪线~
    VC++ : error LNK2005: ... already defined in *.obj
    InstallSheild的一些常量
  • 原文地址:https://www.cnblogs.com/antyi/p/7096814.html
Copyright © 2011-2022 走看看