spring的JdbcTemplate

1. JdbcTemplate

数据库的持久层

2. 如何创建JdbcTemplate

  1. 查看源码
 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();
 }
  1. 构成方法有三个
    我们需要用到的是第二个,在spring容器中配置JdbcTemplate,注入容器即可

3. JdbcTemplate的方法

  1. 基本的方法
jt.execute("insert into account(name,money)values('eee',500)");
  1. 保存方法
jt.update("insert into account(name,money)values(?,?)","fff",5000);
  1. 更新
jt.update("update account set money = money-? where id = ?",300,6);
  1. 删除方法
jt.update("delete from account where id = ?",6);

可以看出增删改方法都是使用update方法去实现,后面接的是可变参数最为sql中的参数

  1. 查询方法
    查询方法可能会遇到的问题,当我们从数据库中查询到数据时,封装到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;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值