Phil Phil - 1 month ago 22
Java Question

JdbcTemplate return if isLast()

I'm using JdbcTemplate to make a request to my database created by Spring Data REST. The requested data will be managed by angularJs.
In the loop of my jdbc.query() I am building a list, which should be returned if the last ResultSet is passed.

But because of the reason that a value must return outside a condition, I have to return null every time the loop for my ResultSet will be passed.

So is there a way to make it better?

Thanks in advance

My code:

List list = new ArrayList();

public List findById(Long id){
return jdbc.query(
sql,
new Object[]{id},
(ResultSet rs, int rowNum) -> {

// code for building list

if(rs.isLast()){
return list;
}

return null;
}
)
}

Answer

1) As i know it's a bad practice to return null. It's better to return empty list.

2) If you need to iterate over result and build list you could use (this is what usually people do):

return jdbcTemplate
      .query( SELECT_ALL_USERS, new ResultSetExtractor<List<User>>() {
        public List<User> extractData( ResultSet resultSet )
          throws SQLException, DataAccessException
        {
          List<User> list = new ArrayList<User>();
          while ( resultSet.next() ) {
            User user = new User(...);  
            list.add( user );
          }
          return list;
        }
      } );   

3) If you want to do something with the last result there is no need to iterate over whole result set , you could use

  List list = new ArrayList();
    if(!resultSet.isBeforeFirst()){
    resultSet.afterLast();
    resultSet.previous();
    User user = new User;
    list.add(user);
    }
    return list;

afterLast() Moves the cursor to the end of this ResultSet object, just after the last row.

previous() Moves the cursor to the previous row in this ResultSet object.

isBeforeFirst returns true if the cursor is before the first row; false if the cursor is at any other position or the result set contains no rows

Useful link: https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html

For passing parameters to your query you could use:

public User getUserByEmail( final String email )
  {
    return jdbcTemplate.query( SELECT_USER_BY_EMAIL, new PreparedStatementSetter() {
      public void setValues( PreparedStatement preparedStatement )
        throws SQLException
      {
        preparedStatement.setString( 1, email );
      }
    }, new ResultSetExtractor<User>() {...}
    } );
  }
Comments