[转] spring JdbcTemplate 查询,使用BeanPropertyRowMapper

[From] http://blog.csdn.net/limenghua9112/article/details/45096437

应用:

使用Spring的JdbcTemplate查询数据库,获取List结果列表,数据库表字段和实体类自动对应,可以使用BeanPropertyRowMapper

注意:

自动绑定,需要列名称和Java实体类名字一致,如:属性名 “userName” 可以匹配数据库中的列字段 "USERNAME" 或 “user_name”。这样,我们就不需要一个个手动绑定了,大大提高了开发效率。


org.springframework.jdbc.core.JdbcTemplate  的 query 方法:
org.springframework.jdbc.core.JdbcTemplate.query(String sql, Object[] args,RowMapper<UserEntity> rowMapper) throws DataAccessException
public class BeanPropertyRowMapper<T> implements RowMapper<T>    注:BeanPropertyRowMapper 实现了 RowMapper 接口

转载请注明:http://blog.csdn.net/limenghua9112/article/details/45096437

查询代码:

[java] view plain copy
 
  1. @Override  
  2.     public List<UserEntity> findUser(UserEntity user) {  
  3.         logger.info("查询语句:" + SEL_BY_USERNAME_PWD);  
  4.   
  5.         /* 
  6.          * Query given SQL to create a prepared statement from SQL and a list of 
  7.          * arguments to bind to the query, mapping each row to a Java object via 
  8.          * a RowMapper. 
  9.          */  
  10.         /* 
  11.          * In Spring 2.5, comes with a handy RowMapper implementation(实现) called 
  12.          * ‘BeanPropertyRowMapper’, which can maps a row’s column value to a 
  13.          * property by matching their names. Just make sure both the property 
  14.          * and column has the same name, e.g property ‘custId’ will match to 
  15.          * column name ‘CUSTID’ or with underscores(底线) ‘CUST_ID’. 
  16.          */  
  17.         List<UserEntity> userList = jdbcTemplate.query(SEL_BY_USERNAME_PWD,  
  18.                 new Object[] { user.getUserName(), user.getPwd() },  
  19.                 new BeanPropertyRowMapper<UserEntity>(UserEntity.class));  
  20.         return userList;  
  21.     }  

SQL:

[java] view plain copy
 
    1. private static final String SEL_BY_USERNAME_PWD = "SELECT * FROM " + ConstantList.T_SHUJU_ADMIN_USER + " AS sp WHERE sp.username = ? and sp.pwd = ?";  
原文地址:https://www.cnblogs.com/pekkle/p/8252556.html