尝试使用Spring-JDBC。我使用this作为参考。我正在尝试获得具有相同姓氏的演员列表。运行此代码给了我想要的结果:
public List<String> getActorsWithSameLastName(String lastName,
NamedParameterJdbcTemplate template) {
String query = "SELECT FIRSTNAME FROM ACTORS WHERE LASTNAME=:LASTNAME";
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("LASTNAME", lastName);
return template.queryForList(query, paramMap, String.class);
}
我有List<String>
个姓氏。如何获得具有列表的演员列表?我是否遍历姓氏列表并每次调用getActorsWithSameLastName()
或者弹簧是否提供了迭代的方式并为我提取结果?请指教。
答案 0 :(得分:30)
使用IN子句..
How to use SELECT IN clause in JDBCTemplates?
List<String> lastnames= new ArrayList<>();
Map namedParameters = Collections.singletonMap("lastnamevalues", lastnames);
StringBuffer recordQueryString = new StringBuffer();
recordQueryString.append("select FIRSTNAME, LASTNAME from ACTORS where lastname in (:lastnamevalues)");
List nameInvolvements = this.namedparameterJdbcTemplate.query(recordQueryString.toString(), namedParameters, new MyMapper());
答案 1 :(得分:11)
您也可以使用MapSqlParameterSource
String query = "SELECT FIRSTNAME FROM ACTORS WHERE LASTNAME in (:LASTNAME)";
Set<String> ids = ....;
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("LASTNAME", ids);
this.namedparameterJdbcTemplate.query(query.toString(), parameters);