[Java] 纯文本查看 复制代码
public class AccountRowMapper implements RowMapper<Account> {
/**
* 需要手动将结果集封装成对象
* @param rs 结果集(数据库里的字段)
* @param i 结果集所在的行: 下标从0开始
* @return 封装好的对象
* @throws SQLException
*/
@Override
public Object mapRow(ResultSet rs, int i) throws SQLException {
//1、新建实体类对象
Account account = new Account();
//2、设置属性值
account.setId(rs.getInt("id"));
account.setUid(rs.getInt("uid"));
account.setMoney(rs.getDouble("money"));
//不同的字段(这里数据库没有,实体类有的字段)
account.setUserId(rs.getInt("id"));
//3、返回对象
return account;
}
}
[Java] 纯文本查看 复制代码
@Test
public void testCustomMapper(){
//1、创建容器
ClassPathXmlApplicationContext ioc =
new ClassPathXmlApplicationContext("applicationContext.xml");
//2、获取工具类对象
JdbcTemplate jd = ioc.getBean(JdbcTemplate.class);
//3、操作数据库
String sql = "select * from account";
List accountList = jd.query(sql, new AccountRowMapper());
accountList.forEach(System.out::println);
}