SQL语句中 如何使用if test来判断某字段是否在list中

背景:
编程语言:java ORM框架:mybatis 和 mybatis-plus

场景描述:

现在需要做一个批量更新的方法,方法传入两个参数:list和fieldNamesList

list是schoolDO对象的List集合,里面是待更新的数据,主键是dataId
schoolDO{

private Long dataId; // 主键
private String schoolNo; // 学校编码
private Integer schoolRank; // 学校排名
private String schoolName; // 学校名称

}
fieldNamesList是对应字段名的字符串
fieldNamesList = ["dataId","schoolNo","schoolRank"];

现在我只想更新schoolNo和schoolRank,根据主键dataId进行更新
如何进行动态sql实现?

我的想法是
dao层java代码方法是

int batchUpdateById(
    @Param("entityList") List<SchoolDO> entityList, 
    @Param("fieldNamesList") List<String> fieldNamesList);

XML文件上这么写(下面是伪代码,因为不会写):

    <!-- 批量插入 -->
    <update id="batchUpdateById">
        <foreach collection="entityList" item="entity" index="index1" open="(" close=")" separator=";">
            update  school_info
            <foreach collection="fieldNamesList" item="fieldName" index="index2" open="(" close=")" separator=",">
                   <if test="test里面判断具体字段是否包含fieldNamesList, 也就是是否和fieldName相等">
                set schoolNo = #{entity.getSchoolNo}
                </if>
                <if test="test里面判断具体字段是否包含fieldNamesList, 也就是是否和fieldName相等">
                set schoolRank = #{entity.getSchoolRank}
                </if>
            </foreach>
            where dataId = #{entity.dataId}
        </foreach>
    </update>

这个是我的想法,不知道有没有大佬知道更好的方法,mytais-plus的批量插入对null的字段不起作用,我这边的需求是,如果是明确在fieldNamesList中的就算是null,也要更新到DB表中,所以不太合适,如果有知道mybatis-plus也能满足需求的,也可以回答

阅读 4.5k
1 个回答

或许你要的是不是:

<update id="batchUpdateById">
    <foreach collection="entityList" item="entity" index="index1" open="(" close=")" separator=";">
        UPDATE school_info SET
        <if test='fieldNamesList.contains("schoolNo")'>
            schoolNo = #{entity.getSchoolNo}
        </if>
        <if test='fieldNamesList.contains("schoolRank")'>
            schoolRank = #{entity.getSchoolRank}
        </if>
        where dataId = #{entity.dataId}
    </foreach>
</update>

希望你帮助到你。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题