java、 JdbcTemplate、MySQL 查询,多个参数,怎么判断

下面这个查询,sql 拼接应该没错吧,主要是 jdbcTemplate.querysql, rowMapper, q, page, perPage; 这个东西怎么传

一开始我想是用 if 判断,如果用 if 判断,3个参数加起来可有 N 种组合呀,如果再多几个参数不就悲剧了,这样的一般怎么写?

java@Override
public List<Pin> searchPinsString q, String category, String c, Integer page, Integer perPage { q = "%" + q + "%"; ifperPage == null { perPage = 20; } ifpage == null || page == 0 { page = 0; } else { page = page - 1 * perPage; } String arg0 = ""; String arg1 = ""; if!StringUtils.isBlankcategory { 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.isBlankc { 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.printlnsql; System.out.printlnq; System.out.printlnpage; System.out.printlnperPage; return jdbcTemplate.querysql, rowMapper, q, page, perPage;
}

笨方法:如果在多几个参数可能就悲剧啦

java @Override public List<Pin> searchPinsString q, String category, String c, Integer page, Integer perPage { q = "%" + q + "%"; ifperPage == null { perPage = 20; } ifpage == null || page == 0 { page = 0; } else { page = page - 1 * perPage; } String arg0 = ""; String arg1 = ""; if!StringUtils.isBlankcategory { arg0 = arg0 + ", tz_board b"; arg1 = arg1 + " AND b.deleting = 0 AND p.board_id = b.board_id AND b.category_id = ?"; } if!StringUtils.isBlankc { 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.isBlankcategory && StringUtils.isBlankc { return jdbcTemplate.querysql, rowMapper, q, category, page, perPage; } else if!StringUtils.isBlankc && StringUtils.isBlankcategory { return jdbcTemplate.querysql, rowMapper, q, c, page, perPage; } else if!StringUtils.isBlankc && !StringUtils.isBlankcategory { return jdbcTemplate.querysql, rowMapper, q, category, c, page, perPage; } return jdbcTemplate.querysql, rowMapper, q, page, perPage; }

发表评论

电子邮件地址不会被公开。 必填项已用*标注