spring的JdbcTemplate
1. JdbcTemplate
数据库的持久层
2. 如何创建JdbcTemplate
- 查看源码
public JdbcTemplate() {
}
public JdbcTemplate(DataSource dataSource) {
this.setDataSource(dataSource);
this.afterPropertiesSet();
}
public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
this.setDataSource(dataSource);
this.setLazyInit(lazyInit);
this.afterPropertiesSet();
}
- 构成方法有三个
我们需要用到的是第二个,在spring容器中配置JdbcTemplate,注入容器即可
3. JdbcTemplate的方法
- 基本的方法
jt.execute("insert into account(name,money)values('eee',500)");
- 保存方法
jt.update("insert into account(name,money)values(?,?)","fff",5000);
- 更新
jt.update("update account set money = money-? where id = ?",300,6);
- 删除方法
jt.update("delete from account where id = ?",6);
可以看出增删改方法都是使用update方法去实现,后面接的是可变参数最为sql中的参数
- 查询方法
查询方法可能会遇到的问题,当我们从数据库中查询到数据时,封装到pojo中需要指明怎么封装。
List<Account> accounts = jt.query("select * from account where money > ? ",
new AccountRowMapper(), 500);
AccountRowMapper类是我们自己写的,我们需要实现RowMapper,中的方法mapRow,用来指定怎么封装数据。
public class AccountRowMapper implements RowMapper<Account>{
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getFloat("money"));
return account;
}
}