spring jdbc.query()建议

问题描述 投票:0回答:1

我需要执行以下查询并获取列表对象。你们知道如何最好地在spring jdbc中进行检索吗?

这是SQL查询:

SELECT app_name, error_code, error_message FROM error_message
WHERE ( 
    (app_name = ? AND error_code = ?) OR 
    (app_name = ? AND error_code = ?) OR 
    (app_name = ? AND error_code = ?) OR 
    (app_name = ? AND error_code = ?) OR 
    (app_name = ? AND error_code = ?) 
)
spring spring-mvc spring-jdbc
1个回答
1
投票
String sql = yoursql; Object args[] = new Object[3]; args[0] = yourparam1; args[1] = yourparam2; args[2] = yourparam3; getJdbcTemplate().query(sql, args, yourRowMapper);

您应该为rowmapper添加以下代码。

private RowMapper yourRowMapper= new YourRowMapperClass ();

public final class YourRowMapperClass implements RowMapper {
   public Object mapRow(ResultSet rs, int rowNum) throws SQLException {

      YourResponse model = new YourResponse ();
      model.setresp1(rs.getDate(1));
      model.setresp2(rs.getDate(2));
      model.setresp3(rs.getString(3));

      return model;
    }
  }

顺序对于指定参数很重要。例如,如果我们在sql中两次使用searchType参数,则应如下定义参数:

Object args[] = new Object[4];
args[0] = searchType;
args[1] = param1;
args[2] = searchType;
args[3] = param2;

如果我们为您定制示例,则可以使用以下代码:

Object args[] = new Object[10];
args[0] = appname;
args[1] = errorcode;
args[2] = appname;
args[3] = errorcode;
args[4] = appname;
args[5] = errorcode;
args[6] = appname;
args[7] = errorcode;
args[8] = appname;
args[9] = errorcode;
© www.soinside.com 2019 - 2024. All rights reserved.