[转] 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值