0 0

使用Mybatis执行sql时如何统一校验输入参数?0

如dao方法有:
void batchInsert(List<User> userList);
List<User> getUsersByIds(List<Long> idList);
void deleteUsersByids(List<Long> idList);

我想若输入参数为空(list.isEmpty()),就不要往下执行sql了,直接返回.否则的话会有错误sql出现,如:
mysql> select * from user where id in () ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1

跟踪源码发现,可以在SqlSesisonTemplate(org.mybatis.spring.SqlSesisonTemplate)中进行处理,如selectList,可以添加如下的逻辑:
if(parameter instanceof List){
  if(((List) parameter).isEmpty()){
List<E> result =  new ArrayList<>();
return result;
  }
  }

但是需要在其他方法中(如insert update delete) 都需要加入差不多的逻辑.
不知除了这一处理方式外,还有没其他更好的方法?
2015年1月18日 22:10

6个答案 按时间排序 按投票排序

0 0

采纳的答案

方法1、创建自定义注解,然后再写一个Mybatis拦截器,拦截 查询相关方法,如果发现 输入参数有自定义注解,并且参数为Null,则直接返回空

方法2、在Service层 对参数做判断,如果参数为空,直接返回,不需要调用DAO层查询

2015年1月20日 15:43
1 0

isnull和isempty标签

2015年1月19日 10:02
0 0

你的sql语句加上标签试试,要确保in 后面不为null

2016年11月29日 10:24
0 0

1 在service层判断参数list是否是null或者长度为0,这样就不调用dao层了
2 sql的写法
<select id="getUsersByIds" resultType="User">
        SELECT
       *
        FROM user
        <if test="idList!=null">
               WHERE id in
            <foreach collection="idList" item="item" index="index"
                 separator="," open="(" close=")">
            #{item}
        </foreach>
            </if>
      
    </select>

2015年10月08日 11:49
0 0

where后面的条件 可以加一个 1=1;
例如
select * from table_a where 1=1
<c:if test='判断表达式'>
    and id in () ;
</c:if>

2015年9月18日 17:20
0 0

切面编程(AOP)应该可以解决这个问题,题主试试

2015年9月16日 15:00

相关推荐

Global site tag (gtag.js) - Google Analytics