Mybatis动态sql查询
来源:互联网 发布:网络售前工程师面试题 编辑:程序博客网 时间:2024/03/29 23:11
很多业务情况下是根据不用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方式
mapper.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攻击!!!!
阅读全文
0 0
- MyBatis动态sql查询
- Mybatis动态sql查询
- mybatis动态sql查询
- mybatis动态sql查询语法
- mybatis动态sql查询语法
- Mybatis动态Sql语句查询
- MyBatis动态查询 模糊查询实例sql
- MyBatis-动态sql与模糊查询 -07
- mybatis 动态SQL与模糊查询
- Mybatis 1.动态sql 2.模糊查询
- Spring+Mybatis实现动态SQL查询
- Spring+Mybatis实现动态SQL查询
- 03. mybatis 动态sql && 模糊查询
- MyBatis 实践 -动态SQL/关联查询
- Mybatis动态SQL与模糊查询
- Mybatis学习----模糊查询和动态sql
- 六、Mybatis动态SQL和模糊查询
- Mybatis之动态SQL 模糊查询
- [Unity&重装系统]重装系统导致Unity 缺失MSVCR100.dll问题解决办法
- TCP首部的URG和PSH
- idea关闭重复代码提示
- 测试一下新的博客
- Linked List Random Node
- Mybatis动态sql查询
- 获取手机设备型号、系统版本、手机型号等信息
- vim学习笔记(usr_04)
- 搜索引擎选择: Elasticsearch与Solr
- 欢迎使用CSDN-markdown编辑器
- 反编译apk获得jar包
- js实现图片上下轮播效果(二)
- ARP协议
- iBatis 和 myBatis中 的“$”符号和“#”