java、 JdbcTemplate、MySQL 查询,多个参数,怎么判断
下面这个查询,sql
拼接应该没错吧,主要是 jdbcTemplate.query(sql, rowMapper, q, page, perPage);
这个东西怎么传
一开始我想是用 if
判断,如果用 if
判断,3个参数加起来可有 N 种组合呀,如果再多几个参数不就悲剧了,这样的一般怎么写?
java
@Override public List<Pin> searchPins(String q, String category, String c, Integer page, Integer perPage) { q = "%" + q + "%"; if(perPage == null) { perPage = 20; } if(page == null || page == 0) { page = 0; } else { page = (page - 1) * perPage; } String arg0 = ""; String arg1 = ""; if(!StringUtils.isBlank(category)) { arg0 = arg0 + ", tz_board b"; arg1 = arg1 + " AND b.deleting = 0 AND p.board_id = b.board_id AND b.category_id = ?"; q = q + ", " + category; } if(!StringUtils.isBlank(c)) { arg0 = arg0 + ", tz_file f"; arg1 = arg1 + " AND p.file_id = f.file_id AND f.theme = ?"; q = q + ", " + c; } String sql = "SELECT p.* FROM tz_pin p" + arg0 + " WHERE p.deleting = 0 AND p.is_private = 0 AND p.raw_text LIKE ?" + arg1 + " ORDER BY p.pin_id DESC LIMIT ?,?"; RowMapper<Pin> rowMapper = new BeanPropertyRowMapper<Pin>(Pin.class); System.out.println(sql); System.out.println(q); System.out.println(page); System.out.println(perPage); return jdbcTemplate.query(sql, rowMapper, q, page, perPage); }
笨方法:如果在多几个参数可能就悲剧啦
java
@Override public List<Pin> searchPins(String q, String category, String c, Integer page, Integer perPage) { q = "%" + q + "%"; if(perPage == null) { perPage = 20; } if(page == null || page == 0) { page = 0; } else { page = (page - 1) * perPage; } String arg0 = ""; String arg1 = ""; if(!StringUtils.isBlank(category)) { arg0 = arg0 + ", tz_board b"; arg1 = arg1 + " AND b.deleting = 0 AND p.board_id = b.board_id AND b.category_id = ?"; } if(!StringUtils.isBlank(c)) { arg0 = arg0 + ", tz_file f"; arg1 = arg1 + " AND p.file_id = f.file_id AND f.theme = ?"; } String sql = "SELECT p.* FROM tz_pin p" + arg0 + " WHERE p.deleting = 0 AND p.is_private = 0 AND p.raw_text LIKE ?" + arg1 + " ORDER BY p.pin_id DESC LIMIT ?,?"; RowMapper<Pin> rowMapper = new BeanPropertyRowMapper<Pin>(Pin.class); if(!StringUtils.isBlank(category) && StringUtils.isBlank(c)) { return jdbcTemplate.query(sql, rowMapper, q, category, page, perPage); } else if(!StringUtils.isBlank(c) && StringUtils.isBlank(category)) { return jdbcTemplate.query(sql, rowMapper, q, c, page, perPage); } else if(!StringUtils.isBlank(c) && !StringUtils.isBlank(category)) { return jdbcTemplate.query(sql, rowMapper, q, category, c, page, perPage); } return jdbcTemplate.query(sql, rowMapper, q, page, perPage); }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论