Spring ResultSetExtractor

2020-07-10 09:12发布

问题:

How to use ResultSetExtractor to retrieve data from database? here I am using oracle 10g as back end. In case of searching an Employee details from Employee Table which one is better to use ResultSetExtractor or RowMapper?

回答1:

One can also use closures (lambdas) as row mapping routine since java 8:

String sql = "select first_name, last_name from PERSON where id = ?";

public Person jdbcTemplate.query(sql,(rs)->{return new Person(rs.getString("first_name"), rs.getString("last_name"));}, int id);

First method param is your query, second - your mapper - Person(String, String) constructor is needed. "first_name", "last_name" are the db-column names. Third - the arg for the id, it's a vararg where you can put more params.



回答2:

A simpler example:

MyDataStructure result = jdbcTemplate.query(sql, new ResultSetExtractor<MyDataStructure>() {

  @Override
  public MyDataStructure extractData(final ResultSet rs) throws ... {
    // collect data from rs here ...
    return myData;
  }
});