1. 程式人生 > >Spring學習筆記(五):Spring JDBC 框架及應用示例

Spring學習筆記(五):Spring JDBC 框架及應用示例

JDBC 框架概述

在使用普通的 JDBC 資料庫時,就會很麻煩的寫不必要的程式碼來處理異常,開啟和關閉資料庫連線等。但 Spring JDBC 框架負責所有的低層細節,從開始開啟連線,準備和執行 SQL 語句,處理異常,處理事務,到最後關閉連線。

所以當從資料庫中獲取資料時,你所做的是定義連線引數,指定要執行的 SQL 語句,每次迭代完成所需的工作。

Spring JDBC 提供幾種方法和資料庫中相應的不同的類與介面。我將給出使用 JdbcTemplate 類框架的經典和最受歡迎的方法。這是管理所有資料庫通訊和異常處理的中央框架類。

JdbcTemplate 類

JdbcTemplate 類執行 SQL 查詢、更新語句和儲存過程呼叫,執行迭代結果集和提取返回引數值。它也捕獲 JDBC 異常並轉換它們到 org.springframework.dao 包中定義的通用類、更多的資訊、異常層次結構。

JdbcTemplate 類的例項是執行緒安全配置的。所以你可以配置 JdbcTemplate 的單個例項,然後將這個共享的引用安全地注入到多個 DAOs 中。

使用 JdbcTemplate 類時常見的做法是在你的 Spring 配置檔案中配置資料來源,然後共享資料來源 bean 依賴注入到 DAO 類中,並在資料來源的設值函式中建立了 JdbcTemplate。

Spring JDBC 示例

準備工作1:啟動mysql,建立一張表 t_user,以便執行CRUD(增、刪、改、查)操作。

create table t_user(
    id int primary key auto_increment,
    username varchar(20),
    password varchar(20),
    account decimal(10,2)
    );

準備工作2:建立一個maven工程,匯入必要依賴,pom檔案配置如下:

<profiles>
        <profile>
            <id>JDK1.8</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <maven.compiler.source>1.8</maven.compiler.source>
                <maven.compiler.target>1.8</maven.compiler.target>
                <encoding>UTF-8</encoding>
            </properties>
        </profile>
  </profiles>
  <dependencies>
    <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-context</artifactId>
       <version>4.3.0.RELEASE</version>
     </dependency>
     <dependency>
       <groupId>org.aspectj</groupId>
       <artifactId>aspectjweaver</artifactId>
       <version>1.8.9</version>
     </dependency>
     <dependency>
       <groupId>cglib</groupId>
       <artifactId>cglib</artifactId>
       <version>3.2.4</version>
     </dependency>
     <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-jdbc</artifactId>
    	<version>5.0.8.RELEASE</version>
	</dependency>
	<dependency>
    	<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
    	<version>6.0.6</version>
	</dependency>
  </dependencies>

準備工作3:建立資料訪問物件介面檔案 UserDAO.java 的內容:

package com.yingshulan.spring_learning.api;

import java.util.List;

public interface UserDAO
{
    /**
     * 新增使用者
     * @param user
     * @return
     * @throws Exception
     */
    public int insertUser(User user) throws Exception;

    /**
     * 修改使用者
     * @param user
     * @param id
     * @return
     * @throws Exception
     */
    public int updateUser(User user, int id) throws Exception;

    /**
     * 刪除使用者
     * @param id
     * @return
     * @throws Exception
     */
    public int deleteUser(int id) throws Exception;

    /**
     * 根據id查詢使用者資訊
     * @param id
     * @return
     * @throws Exception
     */
    public User selectUserById(int id) throws Exception;

    /**
     * 查詢所有的使用者資訊
     * @return
     * @throws Exception
     */
    public List<User> selectAllUser() throws Exception;
}

準備工作4:建立與資料庫中資料表 t_user 對應的實體類 User.java ,這是資料核心,它是真正被操作的實體。

package com.yingshulan.spring_learning.api;

import java.io.Serializable;


public class User implements Serializable
{

    private static final long serialVersionUID = 1L;
    private Integer id;
    private String username;
    private String password;
    private Double account;

    public User()
    {
        super();
    }

    public User(String username, String password, Double account)
    {
        super();
        this.username = username;
        this.password = password;
        this.account = account;
    }

    public Integer getId()
    {
        return id;
    }

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

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    public Double getAccount()
    {
        return account;
    }

    public void setAccount(Double account)
    {
        this.account = account;
    }

    @Override
    public String toString()
    {
        return "UserBean [id=" + id + ", username=" + username + ", password=" + password
                + ", account=" + account + "]";
    }

}

準備工作5:建立 UserMapper.java 檔案的內容,從資料庫中查詢得到的資料是以記錄的形式存在的,並不是一個物件,因此,我們需要建立一個 “對映” 類,將從資料庫中查詢到的記錄 轉化為物件。

package com.yingshulan.spring_learning.api;

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


public class UserMapper implements RowMapper<User> 
{
    public User mapRow(ResultSet rs, int rowNum) throws SQLException 
    {
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setUsername(rs.getString("username"));
        user.setAccount(rs.getDouble("account"));
        user.setPassword(rs.getString("password"));
       return user;
    }
 }

準備工作6:下面是為定義介面 StudentDAO 的實現類檔案 UserJDBCTemplate.java

package com.yingshulan.spring_learning.api;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

public class UserJDBCTemplate implements UserDAO
{
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplateObject;

    public void setDataSource(DataSource dataSource)
    {
        this.dataSource = dataSource;
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }

    @Override
    public int insertUser(User user) throws Exception
    {
        String sql = "insert into t_user (username,password,account) values (?,?,?)";
        jdbcTemplateObject.update(sql, user.getUsername(), user.getPassword(), user.getAccount());
        System.out.println("Created Record: " + user);
        return 0;
    }

    @Override
    public int updateUser(User user, int id) throws Exception
    {
        String sql = "update t_user set username=?,password=?,account=? where id=?";
        jdbcTemplateObject.update(sql, user.getUsername(), user.getPassword(), user.getAccount(),
                user.getId());
        System.out.println("Updated Record: with id = " + id);
        return 0;
    }

    @Override
    public int deleteUser(int id) throws Exception
    {
        String sql = "delete from t_user where id=?";
        jdbcTemplateObject.update(sql, id);
        System.out.println("Deleted Record with id = " + id);
        return 0;
    }

    @Override
    public User selectUserById(int id) throws Exception
    {
        String sql = "select * from t_user where id=?";
        User user = jdbcTemplateObject.queryForObject(sql, new Object[] {id}, new UserMapper());
        ;
        System.out.println("Selected Record with id = " + id);
        return user;
    }

    @Override
    public List<User> selectAllUser() throws Exception
    {
        String sql = "select * from t_user";
        List<User> users = jdbcTemplateObject.query(sql, new UserMapper());
        return users;
    }

}

準備工作7:建立Bean的配置檔案Beansjdbc.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/mysql?useUnicode=true&amp;serverTimezone=UTC"/>
      <property name="username" value="root"/>
      <property name="password" value="123456"/>
   </bean>

   <!-- Definition for UserJDBCTemplate bean -->
   <bean id="UserJDBCTemplate" 
      class="com.yingshulan.spring_learning.api.UserJDBCTemplate">
      <property name="dataSource"  ref="dataSource" />    
   </bean>

</beans>

測試程式碼:

package com.yingshulan.spring_learning.api;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class JDBCTest
{

    public static void main(String[] args) throws Exception
    {
        // TODO Auto-generated method stub
        ApplicationContext context = 
                new ClassPathXmlApplicationContext("Beansjdbc.xml");
         UserJDBCTemplate userJDBCTemplate = 
         (UserJDBCTemplate)context.getBean("UserJDBCTemplate");  
         
         // 1.建立一條記錄
         System.out.println("------Records Creation--------" );
         userJDBCTemplate.insertUser(new User("wangchongyang","1223dfcfdv12",18.5));
         
         //2. 查詢所有記錄
         System.out.println("------Listing Multiple Records--------" );
         List<User> userList = userJDBCTemplate.selectAllUser();
         for (User user : userList)
         {
             System.out.println(user);
         }
         
         //3. 刪除一條記錄
         System.out.println("------Delete Record By ID--------" );
         userJDBCTemplate.deleteUser(3);   
    }
}

執行結果:

------Records Creation--------

Created Record: UserBean [id=null, username=wangchongyang, password=1223dfcfdv12, account=18.5]

------Listing Multiple Records--------
verification.
UserBean [id=1, username=zhangsan, password=abcd1234, account=1234.0]
UserBean [id=2, username=lisi, password=123456789, account=13456.0]
UserBean [id=3, username=wangwu, password=123adfg9, account=34567.0]
UserBean [id=4, username=zhuliu, password=123adfg9, account=34567.0]
UserBean [id=5, username=zhangsan, password=fbdjfvjdf, account=12.5]
UserBean [id=6, username=wangchongyang, password=1223dfcfdv12, account=18.5]

------Delete Record By ID--------
Deleted Record with id = 3

參考部落格: