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>
相关文章推荐
- mybatis 动态sql之Map参数
- mybatis 动态sql之Map参数
- MyBatis动态SQL使用,传入参数Map中的Key判断
- MyBatis动态SQL使用,传入参数Map中的Key判断
- MyBatis动态SQL使用,传入参数Map中的Key判断
- Mybatis 框架 5 - 动态sql返回map或pojo合集
- MyBatis动态SQL使用,传入参数Map中的Key判断
- MyBatis中的动态SQL,实现不确定条件的CRUD-----使用Map来传递查询的参数
- MyBatis动态SQL使用,传入参数Map中的Key判断
- Mybatis动态Sql的Foreach遍历拼接输入参数中的List或数组
- Mybatis 中遍历map 参数中的 list 和 array 属性
- MyBatis动态参数为数组、list、Map,并使用oder by给结果排序
- MyBatis传入参数为集合 list 数组 map写法
- MyBatis框架学习(五)-动态sql
- Mybatis 参数传入集合之foreach动态sql
- mybatis sql in 查询(mybatis sql语句传入参数是list)mybatis中使用in查询时in怎么接收值
- MyBatis传入参数为集合 list 数组 map写法
- Mybatis基础---常用SQL映射标签、多参数设置、resultMap(自定义映射)
- mybatis传递List,Array,Map
- Mybatis(四)输入输出参数、动态sql与关联查询