Mybatis注解上实现动态SQL及in查询

发布于:2022-12-24 ⋅ 阅读:(487) ⋅ 点赞:(0)

目录

动态语句支持以下

Mybatis注解写in查询

动态语句支持以下


trim
where
set
foreach
if
choose
when
otherwise
bind

@Select("<script> " +
        "select * from t_user " +
        "where  1=1 " +
        "<if test='userId!=null'>  and id = #{userId} </if> " +
        "</script>")

List<User> findUser(@Param("userId") Long id);
 

Mybatis注解写in查询

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

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

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

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

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

Map对象没有默认的键。

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

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

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

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

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

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

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

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到