添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

In my UserDao I want to return a list of users.

I already have a UserRowMapper that implements RowMapper<User> .

How can I do this?

I tried:

List rows = getJdbcTemplate().queryforList("select * from users");
for(Map row : rows) {

But wasn't sure how to use my UserRowMapper to populate a User object and insert it into my list of users List.

BTW, is this the best generic list I shoudl be using:

List<User> users = new ArrayList<User>();
                Maybe Dozer (or BeanCopy) could help you convert to the specified object type ? Do check them.
– panzerschreck
                Jan 23, 2012 at 3:21
                An ArrayList should be Good Enough (tm) most of the time. (I.e. when not inserting elements at the beginning / middle of a very very very big list.)
– millimoose
                Jan 23, 2012 at 3:22

Use JdbcTemplate.query(String sql, RowMapper<T> rowMapper, Object... args), and you can pass in a variable number of values for the ? placeholders as the last argument(s):

public List<User> findById(int userId)
    return getJdbcTemplate().query(
            "SELECT * FROM users WHERE user_id=?",
            new UserRowMapper(),
            userId

Or something like:

public List<User> findByManyParams(int param1, int param2, String param3)
    return getJdbcTemplate().query(
            "SELECT * FROM users WHERE foo=? AND bar=? AND foobar=?",
            new UserRowMapper(),
            param1,
            param2,
            param3

The query() method is actually overloaded many times over, so you can usually find at least one flavor that works for what you need in any given situation.

this is perfect and correct example,just wanted to highlight for people who start with JdbcTemplate that in the query the last parameter foobar is String, but when we make query string, we DO NOT NEED to use quotes. Eg. this is correct AND foobar=?, but using quotes is incorrect, eg. this AND foobar='?' will yield an error. (maybe this little comment will help someone avoid a subtle bug) – Dimitry K Feb 27, 2014 at 9:24 but what if I have placeholders in my sql, like "Select * from users where id > ?" when I add parameters, it doesn't compile. – Blankman Jan 23, 2012 at 3:46 @Blankman There's about a zillion overloads for that method listed in the documentation. One of them surely accepts placeholder values. – millimoose Jan 23, 2012 at 12:37

A bit late for this question, but with Lambda expression and RowMapper, below statement worked for me for similar problem.

List<User> users = jdbcTemplate.query("select * from users", (rs, rowNum) -> new User(rs.getString("userId"), rs.getString("userName")));
//la interface RowMapper del modulo Spring JDBC
public class UsuarioMapper implements RowMapper<UsuarioBean>{
    public UsuarioBean mapRow(ResultSet rs, int rowNum) throws SQLException {
        UsuarioBean usuario = new UsuarioBean();
        //se esta realizando el mapeo del bean con las columnas de BD manualmente
        usuario.setIdUsuario(rs.getInt("id_usuario"));
        usuario.setUserName(rs.getString("username"));
        usuario.setClave(rs.getString("clave"));
        usuario.setNombres(rs.getString("nombres"));
        usuario.setPaterno(rs.getString("paterno"));
        usuario.setMaterno(rs.getString("materno"));
        usuario.setCorreo(rs.getString("correo"));
        usuario.setDireccion(rs.getString("direccion"));
        usuario.setTelefono(rs.getString("telefono"));
        usuario.setEstado(rs.getString("estado"));
        usuario.setFec_alta(rs.getDate("fec_alta"));
        return usuario;
public interface UsuarioDao{
    List<UsuarioBean> listarUsuarios();
    UsuarioBean obtenerUsuario(int idUsuario);
    int crearUsuario(UsuarioBean usuario);
    int modificarUsuario(UsuarioBean usuario);
    int eliminarUsuario(int idUsuario);
@Repository//con esto lo subimos al Spring Container
public class UsuarioDaoImpl implements UsuarioDao{
    @Autowired//con esto estamos inyectando UsuarioDaoImpl el jdbcTemplate
    private JdbcTemplate jdbcTemplate;
    @Override
    public List<UsuarioBean> listarUsuarios(){
        String sql="SELECT * FROM USUARIO";
        return jdbcTemplate.query(sql, new UsuarioMapper());
    @Override
    public UsuarioBean obtenerUsuario(int idUsuario){
        String sql="SELECT * FROM USUARIO WHERE ID_USUARIO=?";
        return jdbcTemplate.queryForObject(sql, new Object[]{idUsuario},new UsuarioMapper());
    @Override
    public int crearUsuario(UsuarioBean usuario){
        String sql="INSERT INTO USUARIO(username,clave,nombres,paterno,materno,correo,direccion,telefono,fec_alta,estado) VALUES (?,?,?,?,?,?,?,?,?,?)";
        Object[] params=new Object[]{usuario.getUserName(),usuario.getClave(),usuario.getNombres(),usuario.getPaterno(),usuario.getMaterno(),usuario.getCorreo(),usuario.getDireccion(),usuario.getTelefono(),this.convertirFecha(usuario.getFec_alta()),usuario.getEstado()};
        return jdbcTemplate.update(sql,params);
    @Override
    public int modificarUsuario(UsuarioBean usuario){
        String sql="UPDATE USUARIO SET username=?,clave=?,nombres=?,paterno=?,materno=?,correo=?,direccion=?,telefono=?,estado=? WHERE ID_USUARIO=?";
        Object[] params=new Object[]{usuario.getUserName(),usuario.getClave(),usuario.getNombres(),usuario.getPaterno(),usuario.getMaterno(),usuario.getCorreo(),usuario.getDireccion(),usuario.getTelefono(),usuario.getEstado(),usuario.getIdUsuario()};
        return jdbcTemplate.update(sql,params);
    @Override
    public int eliminarUsuario(int idUsuario){
        String sql="DELETE FROM USUARIO WHERE ID_USUARIO=?";
        return jdbcTemplate.update(sql,new Object[]{idUsuario});
    public java.sql.Date convertirFecha(java.util.Date fecha){
        return new Date((Objects.nonNull(fecha))?fecha.getTime():null);
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.