1. 程式人生 > 其它 >Java EE學習筆記(第四章),JDBC,Spring JdbcTemplate的常用方法

Java EE學習筆記(第四章),JDBC,Spring JdbcTemplate的常用方法

本篇文章,類似於:Spring深入淺出(十四),JDBC,Oracle資料庫基本CRUD操作,以及獲得插入記錄的主鍵值,差別在於:這次是MySQL資料庫。

首先,需要在專案中引用相關包,包括Spring JDBC包、Spring事務驅動包、MySQL資料庫驅動包:

  • spring-jdbc-5.2.3.RELEASE.jar
  • spring-tx-5.2.3.RELEASE.jar
  • mysql-connector-java-5.1.49-bin.jar

一、建立實體類

package com.itheima.jdbc;
public class Account {
    private Integer id;       //
賬戶id private String username; // 使用者名稱 private Double balance; // 賬戶餘額 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 Double getBalance() { return balance; } public void setBalance(Double balance) { this.balance = balance; } public String toString() { return "Account [id=" + id + ", " + "username=" + username + ", balance=" + balance + "]"; } }

二、建立介面類

package com.itheima.jdbc;

import java.util.List;

public interface AccountDao {
    // 新增
    public int addAccount(Account account);

    // 更新
    public int updateAccount(Account account);

    // 刪除
    public int deleteAccount(int id);

    // 通過id查詢
    public Account findAccountById(int id);

    // 查詢所有賬戶
    public List<Account> findAllAccount();
}

三、建立實現類

package com.itheima.jdbc;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class AccountDaoImpl implements AccountDao {
    // 宣告JdbcTemplate屬性及其setter方法
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // 新增賬戶
    public int addAccount(Account account) {
        // 定義SQL
        String sql = "insert into account(username,balance) value(?,?)";
        // 定義陣列來存放SQL語句中的引數
        Object[] obj = new Object[] { account.getUsername(), account.getBalance() };
        // 執行新增操作,返回的是受SQL語句影響的記錄條數
        int num = this.jdbcTemplate.update(sql, obj);
        return num;
    }

    // 更新賬戶
    public int updateAccount(Account account) {
        // 定義SQL
        String sql = "update account set username=?,balance=? where id = ?";
        // 定義陣列來存放SQL語句中的引數
        Object[] params = new Object[] { account.getUsername(), account.getBalance(), account.getId() };
        // 執行新增操作,返回的是受SQL語句影響的記錄條數
        int num = this.jdbcTemplate.update(sql, params);
        return num;
    }

    // 刪除賬戶
    public int deleteAccount(int id) {
        // 定義SQL
        String sql = "delete  from account where id = ? ";
        // 執行新增操作,返回的是受SQL語句影響的記錄條數
        int num = this.jdbcTemplate.update(sql, id);
        return num;
    }

    // 通過id查詢賬戶資料資訊
    public Account findAccountById(int id) {
        // 定義SQL語句
        String sql = "select * from account where id = ?";
        // 建立一個新的BeanPropertyRowMapper物件
        RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
        // 將id繫結到SQL語句中,並通過RowMapper返回一個Object型別的單行記錄
        return this.jdbcTemplate.queryForObject(sql, rowMapper, id);
    }

    // 查詢所有賬戶資訊
    public List<Account> findAllAccount() {
        // 定義SQL語句
        String sql = "select * from account";
        // 建立一個新的BeanPropertyRowMapper物件
        RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
        // 執行靜態的SQL查詢,並通過RowMapper返回結果
        return this.jdbcTemplate.query(sql, rowMapper);
    }

}

四、建立配置檔案

<?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-4.3.xsd">
    <!-- 1配置資料來源 -->
    <bean id="dataSource" class=
     "org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!--資料庫驅動 -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <!--連線資料庫的url -->
        <property name="url" value="jdbc:mysql://localhost:3306/xuejia" />
        <!--連線資料庫的使用者名稱 -->
        <property name="username" value="root" />
        <!--連線資料庫的密碼 -->
        <property name="password" value="admin" />
    </bean>
    <!-- 2配置JDBC模板 -->
    <bean id="jdbcTemplate" 
           class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 預設必須使用資料來源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!--定義id為accountDao的Bean-->
    <bean id="accountDao" class="com.itheima.jdbc.AccountDaoImpl">
        <!-- 將jdbcTemplate注入到accountDao例項中 -->
        <property name="jdbcTemplate" ref="jdbcTemplate" />
    </bean>
    
</beans>

五、建立測試程式

package com.itheima.jdbc;
import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import 
     org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcTemplateTest {
    @Test
    public void mainTest() {
        // 載入配置檔案
        ApplicationContext applicationContext = 
                new ClassPathXmlApplicationContext("applicationContext.xml");
        // 獲取JdbcTemplate例項
        JdbcTemplate jdTemplate = 
                (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
        // 使用execute()方法執行SQL語句,建立使用者賬戶管理表account
        jdTemplate.execute("create table account(" + 
                               "id int primary key auto_increment," +
                               "username varchar(50)," + 
                               "balance double)");
        System.out.println("賬戶表account建立成功!");
    }

//    @Test
    public void addAccountTest() {
        // 載入配置檔案
        ApplicationContext applicationContext = 
                new ClassPathXmlApplicationContext("applicationContext.xml");
        // 獲取AccountDao例項
        AccountDao accountDao = 
                (AccountDao) applicationContext.getBean("accountDao");
        // 建立Account物件,並向Account物件中新增資料
        Account account = new Account();
        account.setUsername("張三");
        account.setBalance(1000.00);
        // 執行addAccount()方法,並獲取返回結果
        int num = accountDao.addAccount(account);
        if (num > 0) {
            System.out.println("成功插入了" + num + "條資料!");
        } else {
            System.out.println("插入操作執行失敗!");
        }
    }
    
//    @Test
    public void updateAccountTest() {
        // 載入配置檔案
        ApplicationContext applicationContext = 
                new ClassPathXmlApplicationContext("applicationContext.xml");
        // 獲取AccountDao例項
        AccountDao accountDao = 
                (AccountDao) applicationContext.getBean("accountDao");
        // 建立Account物件,並向Account物件中新增資料
        Account account = new Account();
        account.setId(2);
        account.setUsername("李四");
        account.setBalance(2000.00);
        // 執行updateAccount()方法,並獲取返回結果
        int num = accountDao.updateAccount(account);
        if (num > 0) {
            System.out.println("成功修改了" + num + "條資料!");
        } else {
            System.out.println("修改操作執行失敗!");
        }
    }
    
//    @Test
    public void deleteAccountTest() {
        // 載入配置檔案
        ApplicationContext applicationContext = 
                new ClassPathXmlApplicationContext("applicationContext.xml");
        // 獲取AccountDao例項
        AccountDao accountDao = 
                (AccountDao) applicationContext.getBean("accountDao");
        // 執行deleteAccount()方法,並獲取返回結果
        int num = accountDao.deleteAccount(2);
        if (num > 0) {
            System.out.println("成功刪除了" + num + "條資料!");
        } else {
            System.out.println("刪除操作執行失敗!");
        }
    }

//    @Test
    public void findAccountByIdTest() {
        // 載入配置檔案
        ApplicationContext applicationContext = 
                new ClassPathXmlApplicationContext("applicationContext.xml");
        // 獲取AccountDao例項
        AccountDao accountDao = 
                (AccountDao) applicationContext.getBean("accountDao");
        // 執行findAccountById()方法
        Account account = accountDao.findAccountById(4);
        System.out.println(account);
    }

//    @Test
    public void findAllAccountTest() {
        // 載入配置檔案
        ApplicationContext applicationContext = 
                new ClassPathXmlApplicationContext("applicationContext.xml");
        // 獲取AccountDao例項
        AccountDao accountDao = 
                (AccountDao) applicationContext.getBean("accountDao");
        // 執行findAllAccount()方法,獲取Account物件的集合
        List<Account> account = accountDao.findAllAccount();
        // 迴圈輸出集合中的物件
        for (Account act : account) {
            System.out.println(act);
        }
    }
}

六、挨個執行

1. 執行mainTest

賬戶表account建立成功!

2. 執行addAccountTest,本處執行3次

成功插入了1條資料!

成功插入了1條資料!

成功插入了1條資料!

3. 執行updateAccountTest

成功修改了1條資料!

4. 執行deleteAccountTest

成功刪除了1條資料!

5. 執行findAccountByIdTest

Account [id=2, username=張三, balance=1000.0]

6. 執行findAllAccountTest

Account [id=2, username=張三, balance=1000.0]
Account [id=3, username=張三, balance=1000.0]