后端开发写Mapper(SQL)遇到的问题
背景
近期做了一个前后端开发,在自己联调的过程中发现了自己容易犯错的地方,大部分是写的SQL不对导致的,不过最终都很快解决了,不过也反映出自己在SQL开发时虽然知识有了但缺乏熟练度。写一个博客记录一下自己犯的错。
错误内容
SQL中批量操作 in
int batchSwitchTenantNodeInfo(@Param("po") List<TenantNodeRef> tenantNodeRefs, @Param("abSuffix") String abSuffix ,@Param("nodeId") String nodeId, @Param("operator") String operator);
<update id="batchSwitchTenantNodeInfo">
update tenant_node_ref
set ab_suffix = #{abSuffix,jdbcType=VARCHAR},
update_time = now(),
update_user = #{operator,jdbcType=VARCHAR}
where is_delete = 0
and node_id = #{nodeId,jdbcType=VARCHAR}
and tenant_id in
(
<foreach collection="po" item="item" index="index" open="" close="" separator=",">
#{item.tenantId, jdbcType=VARCHAR}
</foreach>
)
</update>
这里不熟悉的地方就是对于in的使用,纯手写会忘记一些东西。
SQL中的映射关系
List<T> findPageList(@Param("page") Page var1, @Param("po") T var2);
<!-- 根据条件分页查询列表 -->
<select id="findPageList" resultMap="BaseResultMap" parameterType="com.*.*.*.center.domain.entity.SwitchAbSuffixRecord">
select
<include refid="Base_Column_List"/>
from switch_ab_suffix_record
where is_delete = 0
<if test="po.nodeId != null and po.nodeId != ''">
and node_id = #{po.nodeId,jdbcType=VARCHAR}
</if>
<if test="po.abSuffixNew != null and po.abSuffixNew != ''">
and ab_suffix_new = #{po.abSuffixNew,jdbcType=VARCHAR}
</if>
<if test="po.updateUser != null and po.updateUser != ''">
and update_user = #{po.updateUser,jdbcType=VARCHAR}
</if>
<if test="po.switchMethod != null and po.switchMethod != ''">
and switch_method = #{switchMethod,jdbcType=INTEGER}
</if>
<if test="po.tenantIds != null and po.tenantIds !=''" >
and tenant_ids like CONCAT('%',#{po.tenantIds,jdbcType=VARCHAR},'%')
</if>
ORDER BY id DESC
</select>
这里有几个需要注意的点,也是我很容易犯错的点:
1、查询的字段是所有的字段,但是实体类定义的时候自身只包含了部分字段,其余的字段是通过继承公共类来补充的,这个时候返回值类型就不能直接使用实体类接收,否则会继承的字段就映射不到,需要使用resultMap手动的进行绑定;

浙公网安备 33010602011771号