---
title: "jdbcTemplate 用法"
author: "ryan_ncu"
date: "2009-11-30T11:37:52Z"
tags: []
slug: "jdbctemplate"
draft: false
lastmod: "2009-11-30T11:37:52Z"
id: 537113
url: "https://xkspace.iteye.com/blog/537113"
---

ApplicationContext.xml:

 

&lt;bean id="jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate" &gt;  
         &lt;property name = "dataSource" &gt;  
             &lt;ref bean = "dataSource"  /&gt;  
         &lt;/property &gt;   
&lt;/bean&gt;

 

DAO:

 

@Autowired  
 private JdbcTemplate jdbcTemplate;

 

public List getAllByJDBC() throws SQLException {  
  String sql = "select * from depts";

   RowMapper rowMapper = new DeptRowMapper();  
   List a = jdbcTemplate.query(sql, rowMapper);  
  return a;  
 }

 /\**  
  * 部门映射  
  * @author yanke  
  *  
  \*/  
 private class DeptRowMapper implements RowMapper {  
  @Override  
  public Object mapRow(ResultSet rs, int rowNum) throws SQLException {  
   Dept dept = new Dept();  
   int id = rs.getInt("id");  
   String name = rs.getString("name");  
   dept.setId(id);  
   dept.setName(name);  
   return dept;  
  }  
 }