1. 程式人生 > >第八講:8.1 spring 對JDBC支援

第八講:8.1 spring 對JDBC支援

Spring將替我們完成所有使用JDBC API進行開發的單調乏味的、底層細節處理工作。

操作JDBC時Spring可以幫我們做這些事情:

定義資料庫連線引數,開啟資料庫連線,處理異常,關閉資料庫連線

我們僅需要關注:

宣告SQL語句,處理每一次得到的結果

一個較為簡單的例子與講解

JdbcTemplate類 

JdbcTemplate是core包的核心類。它替我們完成了資源的建立以及釋放工作,從而簡化了我們對JDBC的使用。它還可以幫助我們避免一些常見的錯誤,比如忘記關閉資料庫連線。JdbcTemplate將完成JDBC核心處理流程,比如SQL語句的建立、執行,而把SQL語句的生成以及查詢結果的提取工作留給我們的應用程式碼。它可以完成SQL查詢、更新以及呼叫儲存過程,可以對ResultSet進行遍歷並加以提取。它還可以捕獲JDBC異常並將其轉換成org.springframework.dao包中定義的,通用的,資訊更豐富的異常。

1,複製專案Spring40206 改名為Spring403,beans.xml引入新的名稱空間,引入資料庫連線池dbcp配置,匯入三個jar包(包括jdbc的Mysql驅動包commons-dbcp-1.4.jar,commons-pool.jar,mysql-connector-java-3.1.12-bin.jar),build path,在src下新建dbcp.properties檔案。 beans.xml檔案如下: xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:aop="http://www.springframework.org/schema/aop"     xmlns:context="http://www.springframework.org/schema/context"     xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd        http://www.springframework.org/schema/context            http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="jdbc.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">         <property name="driverClassName" value="${jdbc.driverClassName}"/>         <property name="url" value="${jdbc.url}"/>         <property name="username" value="${jdbc.username}"/>         <property name="password" value="${jdbc.password}"/> bean> beans>dbcp.properties檔案如下:

jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/db_spring jdbc.username=root jdbc.password=root2,在資料庫中新建db_spring資料庫,新建表t_student欄位:id(int 11),name(varchar 22),age(int 11) 3,引入jdbcTemple 的兩個jar包(spring-jdbc-4.0.6.RELEASE.jar,spring-tx-4.0.6.RELEASE.jar),build path 4,在beans.xml中,新增定義id為jdbcTemplate的bean, <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">         <property name="dataSource" ref="dataSource1">property> bean>5.清理無用的包com.cruise.advice,新建包com.cruise.model,Student實體類。新建包com.cruise.dao,studentDao類,寫增加學生方法,修改學生方法,刪除學生方法, 查詢所有學生方法。Student實體類: package com.cruise.model;public class Student {     private int id;     private String name;     private int age;               public Student(String name, int age) {        super();        this.name = name;        this.age = age;     }          public int getId() {        return id;     }     public void setId(int id) {        this.id = id;     }     public String getName() {        return name;     }     public void setName(String name) {        this.name = name;     }     public int getAge() {        return age;     }     public void setAge(int age) {        this.age = age;     } }studentDao介面:package com.cruise.dao;import java.util.List;import com.cruise.model.Student;public interface StudentDao {     public int addStudent(Student student);          public int updateStudent(Student student);          public int deleteStudent(Integer id);          public List findStudents(); }6,新建com.cruise.dao.impl包,StudentDaoImpl類,實現StudentDao介面,後面再繼續寫 7,修改StudentService介面(和StudentDao一樣),以及StudentServiceImpl類,後面再繼續寫 8.在beans.xml中定義id為StudentDao的bean,在StudentDao中注入jdbcTemplate;定義id為StudentService的bean,在StudentService中注入StudentDao <bean id="studentDao1" class="com.cruise.dao.impl.StudentDaoImpl">     <property name="jdbcTemplate" ref="jdbcTemplate1">property> bean> <bean id="studentService" class="com.cruise.service.impl.StudentServiceImpl">     <property name="studentDao" ref="studentDao1">property> bean>9.StudentDaoImpl類中,新增jdbctemplate成員變數,生成set方法,  private JdbcTemplate jdbcTemplate;     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {        this.jdbcTemplate = jdbcTemplate;     }11.StudentServiceImpl類中,引入StudentDao介面,生成set方法,  private StudentDao studentDao;     public void setStudentDao(StudentDao studentDao) {        this.studentDao = studentDao;     }12.StudentDaoImpl中寫新增學生的sql,邏輯程式碼,   @Override     public int addStudent(Student student) {        String sql ="insert into t_student values(null,?,?)";        Object[] params = new Object[]{student.getName(),student.getAge()};        int i = jdbcTemplate.update(sql,params);        return i;     }13.寫測試程式碼。需要Student中新增全參構造方法。 Student類的全參構造,去除id,因為資料庫MySQL是自動生成package com.cruise.test;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.cruise.model.Student;import com.cruise.service.StudentService;public class T {    public static void main(String[] args) {       ClassPathXmlApplicationContext CPXAC=new ClassPathXmlApplicationContext("beans.xml");       StudentService  studentService = (StudentService) CPXAC.getBean("studentService");       studentService.addStudent(new Student("李四", 24));    }}