使用mybatis里面的进行数据库查询,条件是字符串的时候,需要注意一些地方,比如:0 开头,字符串前后带有空格等
具体来看一个例子:
数据库信息:
CREATE TABLE `tache_infos` (
`tch_id` VARCHAR (200),
`tch_name` VARCHAR (1500),
`tch_type` VARCHAR (150)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `tache_infos` (`tch_id`, `tch_name`, `tch_type`) VALUES('0010','开始','es');
INSERT INTO `tache_infos` (`tch_id`, `tch_name`, `tch_type`) VALUES('0022','审核','es');
INSERT INTO `tache_infos` (`tch_id`, `tch_name`, `tch_type`) VALUES('0033','评估','mysql');
情况:
代码:
Xml
<resultMap id="tchInfoMap" type="com.web.mybatisLearn.entity.TacheInfo">
<result column="TCH_ID" jdbcType="VARCHAR" property="typeCode" />
<result column="TCH_NAME" jdbcType="VARCHAR" property="typeName" />
<result column="TCH_TYPE" jdbcType="VARCHAR" property="parentTypeCode" />
</resultMap>
<select id="getTacheList" resultMap="tpTreeTypeMap">
select TCH_ID, TYPE_NAME, TCH_TYPE from TACHE_INFOS
where TCH_TYPE=#{tchType}
<if test="tchIds!=null and tchIds.size()>0">
AND TCH_ID in
<foreach collection="tchIds" index="index" item="tchId" open="(" separator="," close=")">
#{tchId}
</foreach>
</if>
</select>
Mapper:
@MyBatisRepository
public interface TacheInfoMapper {
List<TacheInfo> getTacheList(@Param("tchType") String tchType, @Param("typeIds") List<String> typeIds);
}
注解: MyBatisRepository
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Component
public @interface MyBatisRepository {
String value() default "";
}
参数:
String tchIds = "0010, 0020";
Service:
@Service
public class TacheInfoService {
@Resource
private TacheInfoMapper tacheInfoMapper;
public Object getTacheList(String tchType, String tchIds) {
List<String> typeIdList = Lists.newArrayList(tchIds.split(","));
return tacheInfoMapper.getTacheList(tchType, typeIdList);
}
}
结果:
会查出几条数据来呢? 两条? 一条?还得都没查到
答案是多少呢?
分析:
1,0开头的字符串
使用#{tchId}, 0开头数字字符串,mybatis处理的时候0开头的会被忽略掉,类似excel中数字类型前的0会被默认去掉
处理方式1: 添加类型声明, #{tchId,jdbcType=VARCHAR}
处理方式2: 使用 '${tchId}'
考虑到使用$容易产生注入的风险,因此考虑1第一种方式
修改的后xml
<select id="getTacheList" resultMap="tpTreeTypeMap">
select TCH_ID, TYPE_NAME, TCH_TYPE from TACHE_INFOS
where TCH_TYPE=#{tchType}
<if test="tchIds!=null and tchIds.size()>0">
AND TCH_ID in
<foreach collection="tchIds" index="index" item="tchId" open="(" separator="," close=")">
#{typeCode,jdbcType=VARCHAR}
</foreach>
</if>
</select>
2,空格的影响
修改后,可以查出一条了,为啥还有问题呢? 看日志输出,条件看似没有问题啊?
调试的时候,发现 第二个参数是 " 0020",而不是"0020",问题导致的
处理方式1: 对内容进行trim
List<String> typeIdList = new ArrayList<>();
String[] split = tchIds.split(",");
for (String code : split) {
typeIdList.add(StringUtils.trim(code));
}
处理方式2: 在sql语句入手:
TRIM( #{typeCode,jdbcType=VARCHAR} )
一般考虑用第一种来处理
目前遇到的主要是这两种情况,后续有遇到再补充
总结:
使用mybatis进行查询,参数是字符串的时候,要多留点心。一开始就出问题,可以先使用正常的数据进行查询,然后分析出问题的参数,对比不同,这样更容易发现问题。