SpringBoot在结合mybatis-plus的时候经常需要对某个集合进行遍历,以下是在使用中的记录。
一、版本
使用版本:<mybatis-plus.version>3.2.0</mybatis-plus.version>
二、牛刀小试
1.定义更新实体
代码如下(示例):
@Data
@AllArgsConstructor
@Builder
@ToString
public class DsOwnerChangeDTO {
@ApiModelProperty(value = "owner")
String owner;
@ApiModelProperty(value = "userID")
Integer userId;
@ApiModelProperty(value = "actionid列表")
List<Integer> actionIdsList;
}
2. 定义mapper接口
代码如下(示例):
@Mapper
@Repository
public interface SyncJobMapper extends BaseMapper<SyncJob> {
IPage<SyncJobDTO> queryPage(Page<SyncJobDTO> page, @Param("queryDTO") JobQueryDTO queryDTO);
LinkedList<JobTrendsDTO> getJobsTrend(@Param("trendQuery") TrendQuery trendQuery);
@Select("select a.total_num as totalJobsNum ,b.new_add as todayAddNum\n" +
"from \n" +
"(select count(1) as total_num from sync_job where is_disable = 0) a ,\n" +
"(SELECT count(1) as new_add FROM sync_job where is_disable = 0 and create_time > date_format(now(), '%Y-%m-%d') )b")
TotalJobsDTO getTotalJobsNum();
@Select("SELECT\n" +
"\ta.job_type as type,a.cnt as num,\n" +
"\tCONCAT(ROUND(a.cnt / b.total * 100, 2),'','%') as rate\n" +
"FROM\n" +
"\t(\n" +
"\tselect job_type,count(id) as cnt from sync_job where is_disable = 0 group by job_type\n" +
"\t) a,\n" +
"\t(\n" +
"\tselect count(1) as total from sync_job where is_disable = 0\n" +
"\t) b")
List<JobDistributionDTO> getJobTypeDistribution();
// foreach用在标签中的示例
@Select("<script>" +
"SELECT count(*) FROM `tags` a, (SELECT * FROM `tasks` i1, (SELECT Max(id) as cid FROM `tasks` WHERE `from` = 'TAG' GROUP BY fid) i2 WHERE i1.id = i2.cid ) b WHERE a.name IN " +
"<foreach item='item' index='index' collection='tagNames' open='(' separator=',' close=')' >" +
"#{item}" +
"</foreach>" +
" AND b.state != 'FINISH' AND a.id = b.fid" +
"</script>")
Integer getNotFinishTaskCount(@Param("tagNames") List<String> tagNames);
/**
* 更新 DS owner
*
* @param dsOwnerDTO
* @return
*/
int updateOwnerForDS(@Param("dsOwnerDTO") DsOwnerChangeDTO dsOwnerDTO);
}
3.定义mapper文件xml更新代码
<update id="updateOwnerForDS" parameterType="com.x.dto.DsOwnerChangeDTO">
update sync_job
set owner = #{dsOwnerDTO.owner} ,
owner_user_id = #{dsOwnerDTO.userId}
where action_id in
<foreach collection="dsOwnerDTO.actionIdsList" item="i" index="index" open="(" separator="," close=")">
#{i}
</foreach>
</update>
foreach标签用法说明:
属性 | 描述 |
collection | 表示迭代集合的名称,可以使用@Param注解指定,如下图所示,该参数为必选 ![]() |
item | 表示本次迭代获取的元素,若collection为List、Set或者数组,则表示其中的元素;若collection为map,则代表key-value的value,该参数为必选 |
open | 表示该语句以什么开始,最常用的是左括弧’(’,注意:mybatis会将该字符拼接到整体的sql语句之前,并且只拼接一次,该参数为可选项 |
close | 表示该语句以什么结束,最常用的是右括弧’)’,注意:mybatis会将该字符拼接到整体的sql语句之后,该参数为可选项 |
separator | mybatis会在每次迭代后给sql语句append上separator属性指定的字符,该参数为可选项,一般用于加个, |
index | 在list、Set和数组中,index表示当前迭代的位置,在map中,index代指是元素的key,该参数是可选项 |
总结
提示:在进行传值更新为对象的情况下,务必使用对象点出来,不能使用in 进行在@Update的SQL中进行拼接,发现是无效的。
具体参考快速开始 | MyBatis-Plus