gpt4 book ai didi

java - spring jdbc中如何使用数组

转载 作者:行者123 更新时间:2023-12-01 18:00:45 24 4
gpt4 key购买 nike

我正在使用 spring jdbc 。我的sql查询涉及“IN”子句,我动态创建“?”基于输入并传递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))

}

错误

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

如何在spring jdbc查询方法中使用数组?

最佳答案

更简单的方法是使用可以动态处理 in 子句的 NamedParameterJdbcTemplate。

一个例子是

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));
}

}

关于java - spring jdbc中如何使用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41159786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com