Spring JDBC SqlUpdate類範例


org.springframework.jdbc.object.SqlUpdate類提供了表示SQL更新的可重用操作物件。

使用到的 Student 表的結構如下 -

CREATE TABLE Student(
   ID   INT NOT NULL AUTO_INCREMENT,
   NAME VARCHAR(20) NOT NULL,
   AGE  INT NOT NULL,
   PRIMARY KEY (ID)
);

類的宣告

以下是org.springframework.jdbc.object.SqlUpdate介面的宣告 -

public abstract class SqlUpdate<T>
   extends SqlOperation

用法

  • 步驟1 - 使用組態的資料源建立一個JdbcTemplate物件。
  • 步驟2 - 建立一個實現RowMapper介面的StudentMapper物件。
  • 步驟3 - 使用JdbcTemplate物件方法在使用SqlUpdate物件時進行資料庫操作。

以下範例將演示如何使用SqlUpdate物件進行資料更新操作。首先使用StudentMapper物件將讀取記錄從student表對映到Student物件。

語法

String SQL = "update Student set age = ? where id = ?";

SqlUpdate sqlUpdate = new SqlUpdate(dataSource,SQL);
sqlUpdate.declareParameter(new SqlParameter("age", Types.INTEGER));
sqlUpdate.declareParameter(new SqlParameter("id", Types.INTEGER));
sqlUpdate.compile();

sqlUpdate.update(age.intValue(),id.intValue());

在上程式碼中,

  • SQL - 用於讀取查詢所有學生記錄語句。
  • jdbcTemplateObject - StudentJDBCTemplate物件用於從資料庫中讀取學生記錄。
  • StudentMapper - StudentMapper物件將student表中記錄對映到Student物件。
  • sqlUpdate - SqlUpdate物件用於更新學生記錄。

範例專案

要了解上述與Spring JDBC相關的概念,下面我們編寫一個使用StudentMapper物件進行讀取查詢和對映結果。開啟Eclipse IDE,並按照以下步驟建立一個Spring應用程式,這裡建立一個名稱為:SqlUpdate 的專案。

步驟說明

  1. 參考第一個Spring JDBC專案來建立一個Maven專案 - /20/235/8754.html
  2. 更新bean組態並執行應用程式。

完整的專案結構如下所示 -

以下是Maven組態檔案:pom.xml的程式碼內容:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yiibai</groupId>
    <artifactId>SqlUpdate</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>SqlUpdate</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
    </dependencies>
</project>

以下是資料存取物件介面檔案:StudentDAO.java的內容:

package com.yiibai;

import java.util.List;
import javax.sql.DataSource;

public interface StudentDAO {
    /**
     * This is the method to be used to initialize database resources ie.
     * connection.
     */
    public void setDataSource(DataSource ds);

    /**
     * This is the method to be used to create a record in the Student table.
     */
    public void create(String name, Integer age);

    /**
     * This is the method to be used to list down all the records from the
     * Student table.
     */
    public List<Student> listStudents();

    /**
     * This is the method to be used to update a record into the Student table.
     */
    public void update(Integer id, Integer age);

}

以下是檔案:Student.java的程式碼內容:

package com.yiibai;

public class Student {
    private Integer age;
    private String name;
    private Integer id;

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }
}

以下是檔案:StudentMapper.java的程式碼內容:

package com.yiibai;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class StudentMapper implements RowMapper<Student> {
    public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
        Student student = new Student();
        student.setId(rs.getInt("id"));
        student.setName(rs.getString("name"));
        student.setAge(rs.getInt("age"));
        return student;
    }
}

實現類StudentJDBCTemplate.java實現了定義的DAO介面 - StudentDAO.java,以下是檔案:StudentJDBCTemplate.java的程式碼內容:

package com.yiibai;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.object.SqlQuery;
import org.springframework.jdbc.object.SqlUpdate;

public class StudentJDBCTemplate implements StudentDAO {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplateObject;
    SimpleJdbcInsert jdbcInsert;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
        this.jdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("Student");
    }

    public void create(String name, Integer age) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("name", name);
        parameters.put("age", age);
        jdbcInsert.execute(parameters);
        System.out.println("Created Record Name = " + name + " Age = " + age);
        return;
    }

    public List<Student> listStudents() {
        String sql = "select * from Student";
        SqlQuery<Student> sqlQuery = new SqlQuery<Student>() {

            @Override
            protected RowMapper<Student> newRowMapper(Object[] parameters, Map<?, ?> context) {
                return new StudentMapper();
            }
        };
        sqlQuery.setDataSource(dataSource);
        sqlQuery.setSql(sql);
        List<Student> students = sqlQuery.execute();
        return students;
    }

    public void update(Integer id, Integer age) {
        String SQL = "update Student set age = ? where id = ?";

        SqlUpdate sqlUpdate = new SqlUpdate(dataSource, SQL);
        sqlUpdate.declareParameter(new SqlParameter("age", Types.INTEGER));
        sqlUpdate.declareParameter(new SqlParameter("id", Types.INTEGER));
        sqlUpdate.compile();

        sqlUpdate.update(age.intValue(), id.intValue());
        System.out.println("Updated Record with ID = " + id);
        return;
    }

    public Student getStudent(Integer id) {
        String SQL = "select * from Student where id = ?";
        Student student = jdbcTemplateObject.queryForObject(SQL, new Object[] { id }, new StudentMapper());
        return student;
    }

}

以下是檔案:MainApp.java的程式碼內容:

package com.yiibai;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yiibai.StudentJDBCTemplate;

public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application-beans.xml");

        StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");

        System.out.println("------Records Creation--------");
        studentJDBCTemplate.create("Maxsu", 21);
        studentJDBCTemplate.create("Curry", 22);
        studentJDBCTemplate.create("Suzend", 23);

        System.out.println("----Updating Record with ID = 1 -----");
        studentJDBCTemplate.update(1, 10);

        System.out.println("----Listing Record with ID = 1 -----");
        Student student = studentJDBCTemplate.getStudent(1);
        System.out.print("ID : " + student.getId());
        System.out.print(", Name : " + student.getName());
        System.out.println(", Age : " + student.getAge());

        System.out.println("------Listing Multiple Records--------");
        List<Student> students = studentJDBCTemplate.listStudents();
        for (Student record : students) {
            System.out.print("ID : " + record.getId());
            System.out.print(", Name : " + record.getName());
            System.out.println(", Age : " + record.getAge());
        }
    }
}

以下是檔案:application-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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

    <!-- Initialization for data source -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>

    <!-- Definition for studentJDBCTemplate bean -->
    <bean id="studentJDBCTemplate" class="com.yiibai.StudentJDBCTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

注意: application-beans.xml 檔案的位置是:{workspace}/fistapp/src/main/java 目錄,如果放置錯了,程式可能會因為找不到此組態檔案而出錯。

完成建立原始碼和bean和資料庫連線資訊的檔案組態後,執行應用程式。這裡先簡單說明一下執行的步驟,在專案名稱(SqlUpdate)上點選右鍵,在彈出的選單中選擇:【Run As】-> 【Maven test】

在執行測試成功後,應該會輸出類似以下內容(含有 BUILD SUCCESS 的資訊) 。
接下來,點選類檔案:MainApp.java 選擇【Run As】->【Java Application】,如果應用程式一切正常,這將列印以下結果:

------Records Creation--------
Created Record Name = Maxsu Age = 21
Created Record Name = Curry Age = 22
Created Record Name = Suzend Age = 23
----Updating Record with ID = 1 -----
Updated Record with ID = 1
----Listing Record with ID = 1 -----
ID : 1, Name : Maxsu, Age : 10
------Listing Multiple Records--------
ID : 1, Name : Maxsu, Age : 10
ID : 2, Name : Curry, Age : 22
ID : 3, Name : Suzend, Age : 23