Mybatis动态sql查询
2017-06-19 17:44
330 查看
很多业务情况下是根据不用id来查询需要select * from user where id in (1,2)这样的SQL。现在就提供两种方法实现
方法一:直接拼接插入
mapper.xml<select id="findByIds" parameterType="java.lang.String" resultType="com.pojo.User"> select * from user where id in (${value}) </select> <!-- 注意点: ${}拼接符:字符串原样拼接,如果传入的参数是基本类型(string,long,double,int,boolean,float等),那么${}中的变量名称必须是value -->
@Test public void testfindByIds() throws Exception{ SqlSession openSession = factory.openSession(); //通过getMapper方法来实例化接口 UserMapper mapper = openSession.getMapper(UserMapper.class); //方法一:用直接拼接 List<String> list=new ArrayList<String>(); list.add("1"); list.add("3"); String ids=String.join(",", list); List<User> result = mapper.findByIds(ids); System.out.println(result); }
方法二:foreach方式
ma4000
pper.xml
<select id="findByIds1" parameterType="java.util.List" resultType="com.pojo.User"> select * from user <where> <if test="list.size() != 0"> <!-- foreach:循环传入的集合参数 collection:传入的集合的变量名称 item:每次循环将循环出的数据放入这个变量中 open:循环开始拼接的字符串 close:循环结束拼接的字符串 separator:循环中拼接的分隔符 --> <foreach collection="list" item="id" open="id in(" close=")" separator=","> #{id} </foreach> </if> </where> </select> <!-- 注意点 如果传入是list的话collection必须用list这个名字,而且parameterType必须是java.util.List的写法 -->
@Test public void testfindByIds1() throws Exception{ SqlSession openSession = factory.openSession(); //通过getMapper方法来实例化接口 UserMapper mapper = openSession.getMapper(UserMapper.class); //方法二:传入List List<Integer> ids=new ArrayList<Integer>(); ids.add(1); ids.add(3); List<User> result = mapper.findByIds1(ids); System.out.println(result); }
拼接字符串的方式千万要保证传入的数据是正确,不然的话会存在SQL攻击!!!!
相关文章推荐
- 一步步学Mybatis-怎么样实现动态SQL查询(6)
- MyBatis-动态sql与模糊查询 -07
- 使用MyBatis(12)动态SQL 完成分页查询
- Mybatis学习----模糊查询和动态sql
- mybatis动态sql查询语法
- MyBatis的动态SQL查询-让查询更灵活多变!
- Spring+Mybatis实现动态SQL查询
- MyBatis的动态SQL查询常用几种标签
- 03. mybatis 动态sql && 模糊查询
- myBatis动态Sql查询与PageHelper分页插件
- MyBatis动态SQL与模糊查询
- MyBatis入门07--实现sql动态模糊查询
- mybatis 动态SQL与模糊查询
- Mybatis学习总结之动态SQL与模糊查询
- 利用MyBatis的动态SQL特性抽象统一SQL查询接口
- myBatis学习笔记(6)——动态SQL & 模糊查询
- MyBatis笔记(九)——动态SQL与模糊查询
- Mybatis 1.动态sql 2.模糊查询
- Mybatis动态SQL与模糊查询
- mybatis动态sql查询语法