尝试使用 Jdbctemplate spring 执行带有参数的 SELECT 语句

Trying to do SELECT statement with parameters using Jdbctemplate spring

这是我在使用 traderCode 参数发出请求时遇到的错误:

org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [SELECT * FROM tblCustomer WHERE TraderCode = :traderCode;]; The index 1 is out of range.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: The index 1 is out of range.

参数在Postman中提供: Screenshot

完整的获取请求:

    @GetMapping
    public ResponseEntity<List<Customer>> getCustomers(@RequestParam(required = false) String traderCode, String compCode) {
        try {
            List<Customer> customers = new ArrayList<Customer>();
            JdbcTemplate template = getDataSource(compCode);
            if (traderCode == null){
                customers = template.query("SELECT * FROM tblCustomer;",
                        new BeanPropertyRowMapper<Customer>(Customer.class));
                //customerRepository.findAll().forEach(customers::add);
            } else {
                customers = template.query("SELECT * FROM tblCustomer WHERE TraderCode = :traderCode;",
                        new BeanPropertyRowMapper<Customer>(Customer.class),
                        new MapSqlParameterSource()
                                .addValue("traderCode", traderCode));
                //customerRepository.findByTraderCode(traderCode).forEach(customers::add);
            }

            if (customers.isEmpty())
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);

            return new ResponseEntity<>(customers, HttpStatus.OK);
        } catch (Exception e) {
            System.out.print(e);
            return  new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

您应该按如下方式编辑源代码。

    @GetMapping
    public ResponseEntity<List<Customer>> getCustomers(@RequestParam(required = false) String traderCode, String compCode) {
        try {
            List<Customer> customers = new ArrayList<Customer>();
            JdbcTemplate template = getDataSource(compCode);
            if (traderCode == null || traderCode == ""){
                customers = template.query("SELECT * FROM tblCustomer",
                        new BeanPropertyRowMapper<Customer>(Customer.class));
               
            } else {
                customers = template.query("SELECT * FROM tblCustomer WHERE TraderCode = :TraderCode",
                        new MapSqlParameterSource().addValue("TraderCode", traderCode),
                        new BeanPropertyRowMapper<Customer>(Customer.class));
            }

            if (customers.isEmpty())
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);

            return new ResponseEntity<>(customers, HttpStatus.OK);
        } catch (Exception e) {
            System.out.print(e);
            return  new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }