Spring入门学习笔记(4)——JDBC的使用

Spring JDBC框架概览

使用传统的JDBC连接数据库,需要编写不必要的代码来处理异常、打开和关闭数据库连接等变得非常麻烦。然而,Spring JDBC Framework从打开连接、准备和执行SQL语句、处理异常、处理事务以及最后关闭连接开始,负责所有低级别的细节。

因此,您需要做的就是定义连接参数并指定要执行的SQL语句,并在从数据库获取数据的同时为每个迭代执行所需的工作。

Spring JDBC提供了几种方法和相应不同的类来与数据库进行接口。我将采用经典且最流行的方法来使用框架的JdbcTemplate类。这是管理所有数据库通信和异常处理的中心框架类。

JdbcTemplate类

JDBC模板类执行SQL查询、更新语句、存储过程调用、对结果集执行迭代,并提取返回的参数值。它还捕获JDBC异常,并将其转换为org.springframework.dao中定义的通用的、信息更丰富的包。

一旦配置好,JdbcTemplate类的实例就是线程安全的。因此,您可以配置JdbcTemplate的一个实例,然后将这个共享引用安全地注入多个DAOs。

在使用JDBC模板类时,一个常见的做法是在Spring配置文件中配置一个数据源,然后将这个共享数据源bean注入到DAO类中,然后在数据源的setter中创建JdbcTemplate。

配置数据源

让我们在数据库测试中创建一个数据库表Student。我们假设您正在使用MySQL数据库,如果您使用任何其他数据库,那么您可以相应地更改DDL和SQL查询。

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

现在需要为JDBC模板提供一个DataSource,以便它可以进行配置获取数据库权限:

<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"/>
   <property name = "username" value = "root"/>
   <property name = "password" value = "password"/>
</bean>

数据访问对象(Data Access Object,DAO)

DAO表示数据访问对象,通常用于数据库交互。DAOs的存在是为了提供一种向数据库读写数据的方法,它们应该通过应用程序的其他部分访问它们的接口来公开此功能。

Spring中的DAO支持使得以一致的方式使用JDBC、Hibernate、JPA或JDO等数据访问技术变得很容易。

执行SQL命令

让我们看看如何使用SQL和JDBCTemplate对象对数据库表执行CRUD(创建、读取、更新和删除)操作。

org.springframework.jdbc.core.JdbcTemplate是JDBC核心包中的中心类。它简化了JDBC的使用,有助于避免常见错误。它执行核心JDBC工作流,让应用程序代码提供SQL并提取结果。这个类执行SQL查询或更新,在resultset上发起迭代,捕获JDBC异常,并将它们转换为org.springframework.dao中定义的更通用的、更有用的异常。

注:JdbcTemplate是线程安全的,关于线程安全,将会在后续的文章中加以介绍。

下面介绍使用到的方法,完整信息见Spring JdbcTemplate API Reference

Example

以下项目我使用Maven进行构建,创建Maven项目,更新pom.xml文件为以下内容

<?xml version="1.0" encoding="UTF-8"?>
<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>top.ninwoo.spring</groupId>
    <artifactId>build-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- Spring依赖 -->
        <!-- 1.Spring核心依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <!-- 2.Spring dao依赖 -->
        <!-- spring-jdbc包括了一些如jdbcTemplate的工具类 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <!-- 3.Spring web依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <!-- 4.Spring test依赖:方便做单元测试和集成测试 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
    </dependencies>
</project>
  • StudentDAO.java : 定义Student数据接口
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
      * a record from the Student table corresponding
      * to a passed student id.
   */
   public Student getStudent(Integer id);
   
   /** 
      * 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 delete
      * a record from the Student table corresponding
      * to a passed student id.
   */
   public void delete(Integer id);
   
   /** 
      * This is the method to be used to update
      * a record into the Student table.
   */
   public void update(Integer id, Integer age);
}
  • Student.java : Student类
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 : 将数据库条目映射到Student对象,关于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;
   }
}

这是一个函数接口,因此可以用作lambda表达式或方法引用的赋值目标。

RowMapper必须实现mapRow方法来映射ResultSet中的每一行数据。这个方法不应该调用ResultSet上的next();它只应该映射当前行的值。

@Nullable
T mapRow(java.sql.ResultSet rs,
                   int rowNum)
            throws java.sql.SQLException
Parameters:
rs - the ResultSet to map (pre-initialized for the current row)
rowNum - the number of the current row
Returns:
the result object for the current row (may be null)
Throws:
java.sql.SQLException - if a SQLException is encountered getting column values (that is, there's no need to catch SQLException)
  • StudentJDBCTemplate.java : Student数据接口的具体实现
public class StudentJDBCTemplate implements StudentDAO {
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;
   
   public void setDataSource(DataSource dataSource) {
      this.dataSource = dataSource;
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }
   public void create(String name, Integer age) {
      String SQL = "insert into Student (name, age) values (?, ?)";
      jdbcTemplateObject.update( SQL, name, age);
      System.out.println("Created Record Name = " + name + " Age = " + age);
      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;
   }
   public List<Student> listStudents() {
      String SQL = "select * from Student";
      List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
      return students;
   }
   public void delete(Integer id) {
      String SQL = "delete from Student where id = ?";
      jdbcTemplateObject.update(SQL, id);
      System.out.println("Deleted Record with ID = " + id );
      return;
   }
   public void update(Integer id, Integer age){
      String SQL = "update Student set age = ? where id = ?";
      jdbcTemplateObject.update(SQL, age, id);
      System.out.println("Updated Record with ID = " + id );
      return;
   }
}

构造函数:

  • JdbcTemplate()
  • JdbcTemplate(javax.sql.DataSource dataSource)

update:

public int update(java.lang.String sql,
                  @Nullable
                  java.lang.Object... args)
           throws DataAccessException

queryForObject

<T> T queryForObject(java.lang.String sql,
                               java.lang.Object[] args,
                               RowMapper<T> rowMapper)
                        throws DataAccessException
  • MainApp.java : 主函数
import java.util.List;

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

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

      StudentJDBCTemplate studentJDBCTemplate = 
         (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
      
      System.out.println("------Records Creation--------" );
      studentJDBCTemplate.create("Zara", 11);
      studentJDBCTemplate.create("Nuha", 2);
      studentJDBCTemplate.create("Ayan", 15);

      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());
      }

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

      System.out.println("----Listing Record with ID = 2 -----" );
      Student student = studentJDBCTemplate.getStudent(2);
      System.out.print("ID : " + student.getId() );
      System.out.print(", Name : " + student.getName() );
      System.out.println(", Age : " + student.getAge());
   }
}
  • 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"/>
      <property name = "username" value = "root"/>
      <property name = "password" value = "password"/>
   </bean>

   <!-- Definition for studentJDBCTemplate bean -->
   <bean id = "studentJDBCTemplate" 
      class = "com.tutorialspoint.StudentJDBCTemplate">
      <property name = "dataSource" ref = "dataSource" />    
   </bean>
      
</beans>
  • 输出
------Records Creation--------
Created Record Name = Zara Age = 11
Created Record Name = Nuha Age = 2
Created Record Name = Ayan Age = 15
------Listing Multiple Records--------
ID : 1, Name : Zara, Age : 11
ID : 2, Name : Nuha, Age : 2
ID : 3, Name : Ayan, Age : 15
----Updating Record with ID = 2 -----
Updated Record with ID = 2
----Listing Record with ID = 2 -----
ID : 2, Name : Nuha, Age : 20
posted @ 2018-10-17 22:53  NinWoo  阅读(...)  评论(... 编辑 收藏