超简单Spring入门 (三) Template

首先需要明白的还是同样的问题:template要解决的是什么

用过JDBC的同志们都会发现,实际上直接对数据库进行操作的语句很少,大部分都是一些公式化的语句。

比如:建立数据库连接,异常处理。使用完后关闭连接和result set,同样需要异常处理等等。

这些公式化的语句被称为boilerplate code。

Spring seeks to eliminate boilerplate code by encapsulating it in templates.

Spring’s JdbcTemplate makes it possible to perform database operations without all of the ceremony required by traditional JDBC.

 

例如SimpleJdbcTemplate就可以用来简化JDBC的使用。

public EmployeegetEmployeeById(longid){
 return jdbcTemplate.queryForObject(
  "select id,firstname,lastname,salary"+
  "from employeewhereid=?",
  new RowMapper<Employee>(){
   public EmployeemapRow(ResultSetrs,
    int rowNum)throwsSQLException{
   Employee employee=newEmployee();
   employee.setId(rs.getLong("id"));
   employee.setFirstName(rs.getString("firstname"));
   employee.setLastName(rs.getString("lastname"));
   employee.setSalary(rs.getBigDecimal("salary"));
   return employee;
   }
  },
 id);

}


从上面的例子我们可以看到,大部分代码都是用于查询数据库的语句的内容,而几乎没有在各种准备,附加工作上浪费code。

这里jdbc template是spring定义好的,我们可以直接使用。我们也可以定义自己的template,根据自己的业务逻辑简化代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值