mybatis sql 需要注意的问题

文章目录
  1. 1. 传入参数
  2. 2. 返回结果

mybatis 的映射、数据类型、返回类型以及传参等很容易出现问题,本人总结了下比较容易出现问题的地方以及解决方案

传入参数

1
2
3
<select id="selectList" resultMap="BaseResultMap" parameterType="map">

</select>

像这种定义了参数类型的格式,那么dao 里的定义参数的时候必须传入 map 对应

1
2
3
<select id="selectList" resultMap="BaseResultMap">

</select>

像这种没有定义了参数类型的格式,那么dao 里的定义参数的时候必须定义 params() 与之对应

1
List<Map<String, Object>> getUserInfo(@Param("userId") String userId);
  1. 问题1 参数传0的情况无效
1
2
3
<if test="status != null and status !=''">
AND status = #{status}
</if>

搜索过滤类型或状态的时候,定义了0的情况,则会无效

1
2
3
<if test="status != null and status !='' or status==0">
AND status = #{status}
</if>
  1. 问题2 参数是Date 类型传进来的时候
1
2
3
<if test="strTime != null and strTime !=''">
AND bill_time < #{strTime}
</if>

mybatis 会报错类型不匹配 需要删掉 空字符的判断即可 或者参数以字符串类型传过来

1
2
3
<if test="strTime != null">
AND bill_time < #{strTime}
</if>

返回结果

1
2
3
4
5
6
7
8
9
10
11
12
13
<select id="selectList" resultMap="BaseResultMap">
SELECT a.*
FROM t_base_life_record a
WHERE a.custom_id = #{customId}
ORDER BY a.create_time DESC
</select>
<resultMap id="BaseResultMap" type="com.company.report.dao.model.TBaseRecord">
<result column="life_time" jdbcType="VARCHAR" property="lifeTime"/>
<result column="life_date" jdbcType="VARCHAR" property="lifeDate"/>
<result column="measure" jdbcType="INTEGER" property="measure"/>
<result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
<result column="custom_id" jdbcType="VARCHAR" property="customId"/>
</resultMap>

像这种定义了resultMap格式,那么必须要在mapper定于与之对应,column 必须与之sql 查询字段名对应

1
2
3
4
5
6
<select id="selectList" resultType="com.company.report.dao.model.TBaseRecord">
SELECT a.*
FROM t_base_life_record a
WHERE a.custom_id = #{customId}
ORDER BY a.create_time DESC
</select>

像这种定义了resultType格式,那么必须model 与之sql 查询字段名对应,多表查询的时候是增加字段的时候必须 model 要增加字段,比较麻烦不推荐

[推荐]比较灵活

1
2
3
4
5
6
<select id="selectList" resultType="map">
SELECT a.*
FROM t_base_life_record a
WHERE a.custom_id = #{customId}
ORDER BY a.create_time DESC
</select>

一时想不到其它场景问题,到时有持续更新,如有错误之处请指正……

评论