2016-12-15 79 views
0

我正在使用spring jdbc。我的SQL查询涉及'IN'子句,我动态地创建'?'根据输入并将 对象数组传递给spring jdbc模板的查询方法。如何在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 

如何使用在簧JDBC查询法阵?

回答

1

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

一个例子是

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

} 
相关问题