spring mvc 自己遇到的几个错误

where 1=1  and t.name like '%"话题"%'

 项目采用spring mvc 框架,dao 层 封装数据采用 

private BeanPropertyRowMapper<TopicVO> topicRowMapper = new BeanPropertyRowMapper<TopicVO>(TopicVO.class);

 会自动将 bean 属性与 sql 参数匹配,并加上 ""

where 1=1  and t.name like '%:name%'

 结果就是

where 1=1  and t.name like '%"话题"%'

 所以会 查询不出来结果。解决方案:自己拼装 或者采用 

MapSqlParameterSource paramSource = new MapSqlParameterSource();

paramSource.addValue("name", name);

再或者:

 public int countSearchKey(String key) {
        String sql = "SELECT count(1) FROM bb_app.weibo_metrics_view WHERE instr(duid, '-1')>0 AND upper(content) LIKE :key AND isHidden!=1 AND status!=1";
        MapSqlParameterSource msps = new MapSqlParameterSource();
        msps.addValue("key", "%" + key.toUpperCase() + "%");
        return this.namedJdbcTemplate.queryForInt(sql, msps);
    }
 

sping mvc 注解方式验证 @Valid 会先拦截 绑定bean 的错误信息,如:string 不能转换称int 类型等等。

如果不加@Valid 会遇到刚才说的 转型失败问题。

而且会自动把前端传来的非法值转换。如:int id 前端传a 遇到 @Valid 时候会 将错误信息放到 BdingResult里面,并将id设置默认值为0。但是有一点要注意:必须加上BindingResult result才能接收到错误信息,不会直接throw errors

再一个就是@Valid不会 对多个空格进行空判断,需要手工判断。默认多个空格按照不为空处理。

猜你喜欢

转载自woshixushigang.iteye.com/blog/1559979