使用Spring的JdbcTemplate查询数据库,获取List结果列表,数据库表字段和实体类自动对应,可以使用BeanPropertyRowMapper。
自动绑定,需要列名称和Java实体类名字一致,如:属性名 “userName” 可以匹配数据库中的列字段 "USERNAME" 或 “user_name”。这样,我们就不需要一个个手动绑定了,大大提高了开发效率。
@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 = ?";
spring JdbcTemplate 查询,使用BeanPropertyRowMapper
原文:http://blog.csdn.net/limenghua9112/article/details/45096437