Spring对jdbc的支持

使用步骤:

         1)引入jar文件,需要与事务处理相关jar包

    spring-jdbc-3.2.5.RELEASE.jar

    spring-tx-3.2.5.RELEASE.jar

         2) 优化,JdbcTemplate工具类

    3)连接池配置

    spring对c3p0支持比较完善

    

 1 <!-- 1. 数据源对象: C3P0连接池 -->
 2     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
 3         <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
 4         <property name="jdbcUrl" value="jdbc:mysql:///xxxx"></property>
 5         <property name="user" value="xxxx"></property>
 6         <property name="password" value="xxxx"></property>
 7         <property name="initialPoolSize" value="3"></property>
 8         <property name="maxPoolSize" value="10"></property>
 9         <property name="maxStatements" value="100"></property>
10         <property name="acquireIncrement" value="2"></property>
11     </bean>
12     
13     <!-- 2. 创建JdbcTemplate对象 -->
14     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
15         <property name="dataSource" ref="dataSource"></property>
16     </bean>

  4)dao配置

 1 public class UserDao {
 2     
 3         
 4         //书写set函数是为了使用xml的set方式注入,使用注解可以不要set函数
 5     private JdbcTemplate jdbcTemplate;
 6     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
 7         this.jdbcTemplate = jdbcTemplate;
 8     }
 9 
10     
11     public void save() {
12         String sql = "insert into t_dept(deptName) values('test');";
13         jdbcTemplate.update(sql);
14     }
15     
16     public Dept findById(int id) {
17         String sql = "select * from t_dept where deptId=?";
18         List<Dept> list = jdbcTemplate.query(sql,new MyResult(), id);
19         return (list!=null && list.size()>0) ? list.get(0) : null;
20     }
21     
22     public List<Dept> getAll() {
23         String sql = "select * from t_dept";
24         List<Dept> list = jdbcTemplate.query(sql, new MyResult());
25         return list;
26     }
27     
28     
29     
30     
31     class MyResult implements RowMapper<Dept>{
32 
33         // 如何封装一行记录
34         @Override
35         public Dept mapRow(ResultSet rs, int index) throws SQLException {
36             Dept dept = new Dept();
37             dept.setDeptId(rs.getInt("deptId"));
38             dept.setDeptName(rs.getString("deptName"));
39             return dept;
40         }
41         
42     }        

 

posted @ 2017-09-06 10:33  染红の街道  阅读(154)  评论(0编辑  收藏  举报