应用:
使用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 接口
查询代码:
- @Override
- public List<UserEntity> findUser(UserEntity user) {
- logger.info("查询语句:" + SEL_BY_USERNAME_PWD);
- /*
- * Query given SQL to create a prepared statement from SQL and a list of
- * arguments to bind to the query, mapping each row to a Java object via
- * a RowMapper.
- */
- /*
- * In Spring 2.5, comes with a handy RowMapper implementation(实现) called
- * ‘BeanPropertyRowMapper’, which can maps a row’s column value to a
- * property by matching their names. Just make sure both the property
- * and column has the same name, e.g property ‘custId’ will match to
- * column name ‘CUSTID’ or with underscores(底线) ‘CUST_ID’.
- */
- List<UserEntity> userList = jdbcTemplate.query(SEL_BY_USERNAME_PWD,
- new Object[] { user.getUserName(), user.getPwd() },
- new BeanPropertyRowMapper<UserEntity>(UserEntity.class));
- return userList;
- }
SQL:
- private static final String SEL_BY_USERNAME_PWD = "SELECT * FROM " + ConstantList.T_SHUJU_ADMIN_USER + " AS sp WHERE sp.username = ? and sp.pwd = ?";
转自: http://blog.youkuaiyun.com/limenghua9112/article/details/45096437

本文介绍如何使用Spring的JdbcTemplate结合BeanPropertyRowMapper进行数据库查询操作,通过自动映射数据库列到Java实体类属性,简化了开发过程,提高了开发效率。
661

被折叠的 条评论
为什么被折叠?



