服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Mybatis用注解写in查询的实现

Mybatis用注解写in查询的实现

2021-10-07 11:11小四是个程序员 Java教程

这篇文章主要介绍了Mybatis用注解写in查询的实现方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Mybatis注解写in查询

?
1
2
3
4
5
6
7
@Select("<script>"
        + "SELECT * FROM table WHERE OrderNo IN "
        + "<foreach item='item' index='index' collection='list'      open='(' separator=',' close=')'>"
        + "#{item}"
        + "</foreach>"
        + "</script>")
List<Map<String,Object>> selectdemo(@Param("list") List<String> list);

这里foreach里面的collection值写@Param值。

Mybatis中IN语句查询、Mybatis中的foreach用法

1 需求

查询 用户 ID 为 101、102、103 的数据,参数是一个集合

2 在 SQL 语句中

?
1
select * from t_user where user_id in ( '101' , '102' ,'103')

3 在 Mybatis 中

你只需要

?
1
2
3
4
5
6
7
8
9
<select id="selectUserByIdList" resultMap="usesInfo">
 SELECT
 *
 from t_user
 WHERE id IN
 <foreach collection="idList" item="id" index="index" open="(" close=")" separator=",">
   #{id}
 </foreach>
</select>

对应的 Mapper中的接口如下

?
1
List<UserInfo> selectUserByIdList(@Param("idList")List idList)

 

4 聊一下

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

4.1 collection

用来标记将要做foreach的对象,作为入参时

List对象默认用"list"代替作为键

数组对象有"array"代替作为键,

Map对象没有默认的键。

入参时可以使用@Param(“keyName”)来设置键,设置keyName后,默认的list、array将会失效。

如下的查询也可以写成如下

?
1
List<UserInfo> selectUserByIdList(List idList)
?
1
2
3
4
5
6
7
8
9
<select id="selectUserByIdList" resultMap="usesInfo">
 SELECT
 *
 from t_user
 WHERE id IN
 <foreach collection="list" item="id" index="index" open="(" close=")" separator=",">
   #{id}
 </foreach>
</select>

如果是数组类型

?
1
List<UserInfo> selectUserByIdList(Long[] idList)
?
1
2
3
4
5
6
7
8
9
<select id="selectUserByIdList" resultMap="usesInfo">
 SELECT
 *
 from t_user
 WHERE id IN
 <foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
   #{id}
 </foreach>
</select>

4.2

item:集合中元素迭代时的别名,该参数为必选。

index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选

open:foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选

separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。

close:foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_42322648/article/details/106471902

延伸 · 阅读

精彩推荐