再学习过程中做的关于某一相同字段的数据合并展示,使用动态SQL <foreach>遇到的问题(记录学习)

 

一:查询拥有相同字段的数据

        将需要查询相同字段作为数组传入,在mapper层传入数组,<foreach>一般是和in条件一起使用,collection是数组,需要注意的是在mapper方法中将要传入的数据使用@param注解制定传入参数名。

        mapper层的代码

public interface UserMapper extends BaseMapper<UserDO> {

    /**
     * 分页查询数据
     *
     * @param page  分页信息
     * @param query 查询条件
     * @param address 地址数组            
     * @return 分页数据
     */
    Page<UserDTO> queryPage(Page<?> page, @Param("query") UserPageVO query, 
                            @Param("address") String[] address);

}
 二:将address地址相同的数据合并展示,xml文件
        其中的GROUP_CONCAT是用来合并的nysql函数

查询的结果显示:

这里传入一个数组为空时没有做任何的判断,mybatis会报错,所以需要用<if>标签判断传入的数组是否为空,为空则查找全部地区

 <select id="queryPage" parameterType="com.myzy.talent.biz.business.user.model.vo.UserPageVO" resultType="com.myzy.talent.biz.business.user.model.dto.UserDTO">
        SELECT address,GROUP_CONCAT(id SEPARATOR '、') id,GROUP_CONCAT(uname SEPARATOR '、') uname,GROUP_CONCAT(sex SEPARATOR '、') sex,
        GROUP_CONCAT(age SEPARATOR '、') age,GROUP_CONCAT(email SEPARATOR '、') email
        FROM biz_user
            <where>
            <if test="query.uname != null and query.uname != ''">
                AND uname LIKE CONCAT('%',#{query.uname},'%')
            </if>
            <if test="query.sex != null and query.sex != ''">
                AND sex LIKE CONCAT('%',#{query.sex},'%')
            </if>
            <if test="query.age != null and query.age != ''">
                AND age LIKE CONCAT('%',#{query.age},'%')
            </if>
            <if test="query.address != null and query.address.length > 0">
                AND address IN
                <foreach collection="address" item="item" open="(" close=")"  separator=",">
                    #{item}
                </foreach>
            </if>
            <if test="query.address == null and query.address.length == 0">
                AND address
            </if>
            <if test="query.email != null and query.email != ''">
                AND email LIKE CONCAT('%',#{query.email},'%')
            </if>
            </where>
        GROUP BY address
    </select>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值