Type of mismatch: cannot be converted from the list <Map <String, Object >> to the list <Object>

We have

 String sql = "SELECT * FROM user WHERE id = '" +userId +"'";
 List<Object> userList = template.queryForList(sql);

The request should return different users with this identifier. templateis an object of a class JdbcTemplate.
Here, the query returns a list Map<String,Object>, and the left side - List<Object>. Is there any way to do the conversion. This is part of the spring transaction management example.

+4
source share
3 answers

You can always use only those valuesthat interest you, for example:

List<Object> userList = new ArrayList<Object>(template.queryForList(sql).values());

If it returns List<Map<String, Object>>instead Map<String,Object>:

List < Object > userList = new ArrayList < Object > ();
for (Map < String, Object > obj: template.queryForList(sql)) {
    userList.addAll(obj.values());
}

Object . , Map.values() , ArrayList , : HashMap

+2

, . Spring , , RowMapper . , , PreparedStatement s. SQL-.

, :

template.query("SELECT * FROM user WHERE id = ?", new Object[] { userId }, new RowMapper<User>() {

    public User mapRow(ResultSet rs, int rowNum) {
        // Build a user from the current row and return it
    }

});
+1

, . - , . :

:

1. UserID -> Type: Int
2. User_Name -> Type: Varchar
3. User_Contact -> Type: Varchar
...

Now you can simply write RowMapper to map all of these fields to your own POJO object, for example:

POJO Class:

public class User{
     private int userId;
     private String userName;
     private String userContact;

     public int getUserId() {
          return this.userId;
     }

     public void setUserId(int userId) {
          this.userId = userId;
     }

     /* Other Getter-Setter(s) */
}

Query String:

private static final String SELECT_QUERY = "SELECT * FROM user WHERE id = ?";

JdbcTemplate Call: Here you go userIdfor ?. JdbcTemplate will take care of this automatically.

List<User> = (List<User>) jdbcTemplate.query(SELECT_QUERY, new Object[] { userId }, new UserRowMapper());

Finally, the UserRowMapper class:

class UserRowMapper implements RowMapper {

  @Override
  public Object mapRow(ResultSet resultSet, int row) throws SQLException {
    User user = new User();

    user.setUserId(resultSet.getInt("UserID"));
    user.setUserName(resultSet.getString("User_Name"));
    user.setUserContact(resultSet.getString("User_Contact"));

    return user;
  }
}

This is really the best and recommended way to use JdbcTemplate.

+1
source

Source: https://habr.com/ru/post/1622788/


All Articles