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); }
点点点点点
9 years, 11 months ago