简体   繁体   English

如何在Spring JDBC中使用数组

[英]How to use array in spring jdbc

I am using spring jdbc . 我正在使用spring jdbc。 My sql query involves 'IN' clause, I dynamically creates the '?' 我的SQL查询涉及“ IN”子句,我动态创建“?” based on input and pass the array of object to query method of spring jdbc template. 基于输入并将对象数组传递给spring jdbc模板的查询方法。

 public  List<Student> getStudentName(String studentId){
  //studentId contains  number of ids sepeated by comma.
 Object [] params= new Object[]{studentId.split(",")}
  Stream<String>  stream= Arrays.stream(studentId.split(","));

 final String stInClauseParameters= stream.map(studentId -> "?").collect((Collectors.joining(",")));


  StringBuilder sql = new StringBuilder();
  sql.append(" select studentName from Student where  student_id IN ("+stInClauseParameters+")")
  return JdbcTemplate.query(sql.toString(),params, new BeanPropertyRowMapper(Student.class))

  }

The error 错误

Prepared Statement: Input parameter not set, index: 1.; nested exception is java.sql.SQLException: JZ0SA: Prepared Statement: Input parameter not set, index: 1

How to use array in spring jdbc query method ? Spring JDBC查询方法中如何使用数组?

An easier way would be to use a NamedParameterJdbcTemplate that can dynamically handle the in clause for you. 一种更简单的方法是使用可以为您动态处理in子句的NamedParameterJdbcTemplate。

An example would be 一个例子是

public class StudentDao extends JdbcDaoSupport {


public List<Student> getStudentName(String studentId) {

    List<String> studentIds = Arrays.asList(studentId.split(","));
    String sql = "SELECT studentName FROM Student WHERE student_id IN (:ids)";

    Map<String, List<String>> params = new HashMap<String, List<String>>();
    params.put("ids", studentIds);

    NamedParameterJdbcTemplate template = new    NamedParameterJdbcTemplate(getDataSource());
    return template.query(sql, params, new BeanPropertyRowMapper(Student.class));
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM