spring JdbcTemplate 查询,使用BeanPropertyRowMapper

应用:

使用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

查询代码:

@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 = ?";




郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。