您的位置:首页 > 数据库

Mybatis 框架 6 - 动态SQL_单参数List、单参数Array、多参数Map

2017-10-30 19:55 651 查看

1.动态sql foreach遍历

主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。

foreach元素的属性主要有 item,index,collection,open,separator,close。

组装sql条件 id in (1,2,3)

item : 表示集合中每一个元素进行迭代时的别名

index : 指定一个名字,用于表示在迭代过程中,每次迭代到的位置

open : 表示该语句以什么开始

separator : 表示在每次进行迭代之间以什么符号作为分隔 符

close : 表示以什么结束

collection属性,该属性是必须指定的,但是在不同情况 下,

该属性的值是不一样的,主要有一下3种情况:

如果传入的是单参数且参数类型是一个List的时候,collection属性值为 list

如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为 array

如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,(collection的参数取map的key值)

a. 单参数List的类型

//接口UserDao.java
public List<UserInfo> getUserList(List<Integer> list) throws SQLException;


传入一个集合

<!--UserDao.xml -->
<select id = "getUserList" resultType = "UserInfo">
select * from UserInfo where id in
<!--foreach内各值作用看上面讲解 -->
<foreach collection="list" item="iditem" open="(" separator="," close=")">#{iditem}</foreach>
</select>


b. 单参数array数组的类型

//接口UserDao.java
public List<UserInfo> getUserList2(int[] ids) throws SQLException;


传入一个整型数组

<!--UserDao.xml -->
<select id = "getUserList2" resultType = "UserInfo">
select * from UserInfo where id in
<foreach collection="array" item="iditem" open="(" separator="," close=")">#{iditem}</foreach>
</select>


c. 自己把参数封装成Map的类型(多或单参数)

//接口UserDao.java
List<Map<String,Object>>  getUserMapList(UserInfo user)  throws SQLException;


//test.java
ArrayList<Integer> al=new ArrayList<>();
al.add(99);
al.add(98);
al.add(97);

HashMap<String, ArrayList<Integer>> map=new HashMap<>();
map.put("ids", al);
map.put("ename","王五")


<!--UserDao.xml -->
<select id="getUserListMap"  resultType="UserInfo">
select * from userinfo where id in
<foreach collection="ids" item="iditem" open="(" separator="," close=")">#{iditem}</foreach>
<!--直接取key值-->
and ename like '%${ename}%'
</select>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: