在使用MyBatisPlus来匹配身份证后6位时遇到了likeLeft和likeRight的问题:
likeLeft时匹配最左边还是匹配最右边?
所以来一个简单的测试(通过打印 “成功/失败” 来判断)
MyBatisPlus代码:
default boolean bindStudent(AppUserBindVO appUserBindVO){
String idLastSix = appUserBindVO.getIdLastSix(); // 获取 appUserBindVO 对象的后六位字符串
return exists(new LambdaQueryWrapperX<StudentDO>()
.eqIfPresent(StudentDO::getStudentNumber,appUserBindVO.getNumber())
.eqIfPresent(StudentDO::getName,appUserBindVO.getName())
.eqIfPresent(StudentDO::getMobile,appUserBindVO.getMobile())
.likeLeft(StudentDO::getIdCard, idLastSix)
);
}
@Override
public boolean bindStudent(AppUserBindVO appUserBindVO) {
if (studentMapper.bindStudent(appUserBindVO)){
System.out.println("绑定成功");
}else System.out.println("绑定失败");
return studentMapper.bindStudent(appUserBindVO);
}
MySQL:
用Apifox通过身份证后6位请求,绑定成功
用Apifox通过身份证前6位请求,绑定失败
究其源码:
public Children like(boolean condition, R column, Object val) {
return this.likeValue(condition, SqlKeyword.LIKE, column, val, SqlLike.DEFAULT);
}
public Children likeLeft(boolean condition, R column, Object val) {
return this.likeValue(condition, SqlKeyword.LIKE, column, val, SqlLike.LEFT);
}
public Children likeRight(boolean condition, R column, Object val) {
return this.likeValue(condition, SqlKeyword.LIKE, column, val, SqlLike.RIGHT);
}
//===============================================================================
protected Children likeValue(boolean condition, SqlKeyword keyword, R column, Object val, SqlLike sqlLike) {
return this.maybeDo(condition, () -> {
this.appendSqlSegments(this.columnToSqlSegment(column), keyword, () -> {
return this.formatParam((String)null, SqlUtils.concatLike(val, sqlLike));
});
});
}
//==============================================================================
public static String concatLike(Object str, SqlLike type) {
switch(type) {
case LEFT:
return "%" + str;
case RIGHT:
return str + "%";
default:
return "%" + str + "%";
}
}
最后发现 LEFT 是在左边加 “%” , 所以likeLeft匹配的是右边
likeRight则是匹配左边,like则是都可以匹配