passing different types of arguments to jdbctemplate query

[亡魂溺海] 提交于 2020-05-09 01:26:42

问题


I am trying to retrieve records from the database by using where clause with few different types of arguments. This is the simple method which I wrote where I am passing breedId and gender as an arguments.

public List<Dog> listByBreedIdAndGender(long breedId, String gender) {  
  return query("SELECT * FROM dog_entity WHERE breed__id = ? AND gender = ?",
          new MapSqlParameterSource(":breedId", breedId)
          .addValue(":gender", gender));
 }

private List<Dog> query(String sql, MapSqlParameterSource parameters) {  
  List<Dog> dogs = jdbcTemplate.query(sql, new DogRowMapper(), parameters);
  return dogs;
 }

I ran this method but got below exception. Can anyone let me know how to pass multiple arguments to the jdbcTemplate.query(), I am kinda new to it.

{
timestamp: 1419637479460
status: 500
error: "Internal Server Error"
exception: "org.springframework.dao.TransientDataAccessResourceException"
message: "PreparedStatementCallback; SQL [SELECT * FROM dog_entity WHERE breed__id = ? AND gender = ?]; Invalid argument value: java.io.NotSerializableException; nested exception is java.sql.SQLException: Invalid argument value: java.io.NotSerializableException"
path: "/api/2/m"
}

回答1:


Please use

public List<Dog> listByBreedIdAndGender(long breedId, String gender) {  
   return jdbcTemplate.query("SELECT * FROM dog_entity WHERE breed__id = :breedId AND gender =:gender", 
      new MapSqlParameterSource()
      .addValue("breedId", breedId)
      .addValue("gender", gender));
}

Please make sure the jdbcTemplate is NamedParameterJdbcTemplate .

If you need to use JdbcTemplate then

    public List<Dog> listByBreedIdAndGender(long breedId, String gender) {  
       return jdbcTemplate.query
          ("SELECT * FROM dog_entity WHERE breed__id = ? AND gender = ?",
          new Object[] { breedId, gender }, 
          new DogRowMapper());         
    }

or if you insist on usage of the private query method

public List<Dog> listByBreedIdAndGender(long breedId, String gender) {  
       return query
          ("SELECT * FROM dog_entity WHERE breed__id = ? AND gender = ?",
          new Object[] { breedId, gender });         
}

private List<Dog> query(String sql, Object[] parameters) {  
   List<Dog> dogs = jdbcTemplate.query(sql, parameters, new DogRowMapper());
   return dogs;

}

Please make sure breed__id has correct number of _ characters.

The concept is to either use NamedParameterJdbcTemplate with parameters designated by :name (such as :gender) or simple JdbcTemplate with positional parameters (such as new Object[] { breedId, gender } where breedId matches the first ? and the gender the second ?).



来源:https://stackoverflow.com/questions/27663170/passing-different-types-of-arguments-to-jdbctemplate-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!