mybatis条件遍历<foreach> 一个字段多个值 排序

it2024-10-20  38

业务场景:  根据某字段进行排序,字段有多个值

例如:  顾客想看电影,顾客优先想看 恐怖 片,次选 喜剧 片,其他的排在后面。

简单的 movie  表:   name ,  url  ,type

基本 sql:  

select  name ,url    from  movie  order by type  like ' type'

很显然,基本sql实现不了需求    (我不会) 

 

在  mybatis  中可使用<foreach> 标签实现:

types 列表有两个字段  (恐怖,喜剧)

mapper 接口 :

List<Movie> selectMovieByType (@Param("types") List<types> types);

mapper.xml  :

<select id="selectMovieByType" resultMap="movieMap"> select  name ,url    from  movie  <if test="types!= null and types.size>0"> order by <foreach collection="types" item="type" open=" " close=" " separator=","> type like CONCAT(CONCAT('%',#{type}), '%')      desc </foreach> </if> </select>

 

foreach 说明:

item:集合中元素迭代时的别名,该参数为必选。index:在list和数组中,index是元素的序号,在map中,index是元素的key,item是元素的value,该参数可选open:foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。close: foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。

 

友情提示:  order by  一定要放在<if>标签中。  因为如果 types 列表是空的,order by 后面是无参数的,会引起EOFParserException 异常。   细节问题,我是大意放错过位置。

最新回复(0)