應用:
使用Spring的JdbcTemplate查詢數據庫,獲取List結果列表,數據庫表字段和實體類自動對應,可以使用BeanPropertyRowMapper。
注:BeanPropertyRowMapper 實現了 RowMapper 接口。
注意:
自動綁定,需要列名稱和Java實體類名字一致,如:屬性名 “userName” 可以匹配數據庫中的列字段 "USERNAME" 或 “user_name”。這樣,我們就不需要一個個手動綁定了,大大提高了開發效率。
查詢代碼:
@Override
public List<UserEntity> findUser(UserEntity user) {
logger.info("查詢語句:" + SEL_BY_USERNAME_PWD);
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 = ?";