spring筆記03

[toc]

JdbcTemplate概述

JdbcTemplate是Spring框架中提供的一個對象,對原始的JDBC API進行簡單封裝,其用法與DBUtils類似.

JdbcTemplate對象的創(chuàng)建

  1. 配置數(shù)據(jù)源: 與DBUtils中的QueryRunner對象類似,JdbcTemplate對象在執(zhí)行sql語句時也需要一個數(shù)據(jù)源,這個數(shù)據(jù)源可以使用C3P0或者DBCP,也可以使用Spring的內(nèi)置數(shù)據(jù)源DriverManagerDataSource.

    1. 配置C3P0數(shù)據(jù)源:

      使用C3P0數(shù)據(jù)源,需要在bean.xml中配置如下:

      <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
          <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
          <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/數(shù)據(jù)庫名"></property>
          <property name="user" value="用戶名"></property>
          <property name="password" value="密碼"></property>
      </bean>
      
    2. 配置DBCP數(shù)據(jù)源

      使用DBCP數(shù)據(jù)源,需要在bean.xml中配置如下:

      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
          <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
          <property name="url" value="jdbc:mysql://localhost:3306/數(shù)據(jù)庫名"></property>
          <property name="username" value="用戶名"></property>
          <property name="password" value="密碼"></property>
      </bean>
      
    3. 使用Spring內(nèi)置的數(shù)據(jù)源DriverManagerDataSource,需要在bean.xml中配置如下:

      <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
          <property name="url" value="jdbc:mysql://localhost:3306/數(shù)據(jù)庫名"></property>
          <property name="username" value="用戶名"></property>
          <property name="password" value="密碼"></property>
      </bean>
      
  1. 創(chuàng)建JdbcTemplate對象:

    JdbcTemplate中注入數(shù)據(jù)源創(chuàng)建對象,在bean.xml中配置如下:

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    

JdbcTemplate的增刪改查操作

使用JdbcTemplate實現(xiàn)增刪改

DBUtils十分類似,JdbcTemplate的增刪改操作使用其update("SQL語句", 參數(shù)...)方法

  1. 增加操作

    public static void main(String[] args) {
        //1.獲取Spring容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根據(jù)id獲取JdbcTemplate對象
        JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
        //3.執(zhí)行增加操作
        jt.update("insert into account(name,money)values(?,?)","名字",5000);
    }
    
  2. 刪除操作

    public static void main(String[] args) {
        //1.獲取Spring容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根據(jù)id獲取JdbcTemplate對象
        JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
        //3.執(zhí)行刪除操作
        jt.update("delete from account where id = ?",6);
    }
    
  3. 更新操作

    public static void main(String[] args) {
        //1.獲取Spring容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根據(jù)id獲取JdbcTemplate對象
        JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
        //3.執(zhí)行更新操作
        jt.update("update account set money = money-? where id = ?",300,6);
    }
    

使用JdbcTemplate實現(xiàn)查詢

DBUtils十分類似,JdbcTemplate的查詢操作使用其query()方法,其參數(shù)如下:

  • String sql: SQL語句
  • RowMapper<T> rowMapper: 指定如何將查詢結(jié)果ResultSet對象轉(zhuǎn)換為T對象
  • @Nullable Object... args: SQL語句的參數(shù)

其中RowMapper類類似于DBUtilsResultSetHandler類,可以自己寫一個實現(xiàn)類,但常用Spring框架內(nèi)置的實現(xiàn)類BeanPropertyRowMapper<T>(T.class)

  1. 查詢所有:

    public List<Account> findAllAccounts() {
        List<Account> accounts = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
        return accounts;
    }
    
  2. 查詢一條記錄:

    public Account findAccountById(Integer accountId) {
        List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
        return accounts.isEmpty() ? null : accounts.get(0);
    }
    
  3. 聚合查詢:

    JdbcTemplate中執(zhí)行聚合查詢的方法為queryForObject()方法,其參數(shù)如下:

    • String sql: SQL語句

    • Class<T> requiredType: 返回類型的字節(jié)碼

    • @Nullable Object... args: SQL語句的參數(shù)

      public static void main(String[] args) {
          //1.獲取Spring容器
          ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
          //2.根據(jù)id獲取JdbcTemplate對象
          JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
          //3.聚合查詢
          Integer total = jt.queryForObject("select count(*) from account where money > ?", Integer.class, 500);
          System.out.println(total);
      }
      

在DAO層使用JdbcTemplate

在DAO層直接使用JdbcTemplate

在DAO層使用JdbcTemplate,需要給DAO注入JdbcTemplate對象.

public class AccountDaoImpl implements IAccountDao {
    
    private JdbcTemplate jdbcTemplate;  // JdbcTemplate對象

    // JdbcTemplate對象的set方法
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // DAO層方法
    @Override
    public Account findAccountById(Integer id) {
        // 實現(xiàn)...
    }

    // DAO層方法
    @Override
    public Account findAccountByName(String name) {
        // 實現(xiàn)...
    }

    // 其它DAO層方法...
}

DAO層對象繼承JdbcDaoSupport類

在實際項目中,我們會創(chuàng)建許多DAO對象,若每個DAO對象都注入一個JdbcTemplate對象,會造成代碼冗余.

  • 實際的項目中我們可以讓DAO對象繼承Spring內(nèi)置的JdbcDaoSupport類.在JdbcDaoSupport類中定義了JdbcTemplateDataSource成員屬性,在實際編程中,只需要向其注入DataSource成員即可,DataSource的set方法中會注入JdbcTemplate對象.
  • DAO的實現(xiàn)類中調(diào)用父類的getJdbcTemplate()方法獲得JdbcTemplate()對象.

JdbcDaoSupport類的源代碼如下:

public abstract class JdbcDaoSupport extends DaoSupport {
    
    @Nullable
    private JdbcTemplate jdbcTemplate;  // 定義JdbcTemplate成員變量

    public JdbcDaoSupport() {
    }

    // DataSource的set方法,注入DataSource時調(diào)用createJdbcTemplate方法注入JdbcTemplate
    public final void setDataSource(DataSource dataSource) {
        if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {
            this.jdbcTemplate = this.createJdbcTemplate(dataSource);
            this.initTemplateConfig();
        }
    }

    // 創(chuàng)建JdbcTemplate,用來被setDataSource()調(diào)用注入JdbcTemplate
    protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    // JdbcTemplate的get方法,子類通過該方法獲得JdbcTemplate對象
    @Nullable
    public final JdbcTemplate getJdbcTemplate() {
        return this.jdbcTemplate;
    }

    @Nullable
    public final DataSource getDataSource() {
        return this.jdbcTemplate != null ? this.jdbcTemplate.getDataSource() : null;
    }

    public final void setJdbcTemplate(@Nullable JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
        this.initTemplateConfig();
    }

    // ...
}

bean.xml中,我們只要為DAO對象注入DataSource對象即可,讓JdbcDaoSupport自動調(diào)用JdbcTemplate的set方法注入JdbcTemplate

<?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.xsd">

    <!-- 配置數(shù)據(jù)源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/數(shù)據(jù)庫名"></property>
        <property name="username" value="用戶名"></property>
        <property name="password" value="密碼"></property>
    </bean>

    <!-- 配置賬戶的持久層-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <!--不用我們手動配置JdbcTemplate成員了-->
        <!--<property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

</beans>

在DAO類接口中,我們不需定義JdbcTemplate成員變量,只需定義并實現(xiàn)DAO層方法即可.

public interface IAccountDao {
    
    // 根據(jù)id查詢賬戶信息
    Account findAccountById(Integer id);

    // 根據(jù)名稱查詢賬戶信息
    Account findAccountByName(String name);

    // 更新賬戶信息
    void updateAccount(Account account);
}

在實現(xiàn)DAO接口時,我們通過super.getJdbcTemplate()方法獲得JdbcTemplate對象.

public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
    
    @Override
    public Account findAccountById(Integer id) {
        //調(diào)用繼承自父類的getJdbcTemplate()方法獲得JdbcTemplate對象
        List<Account> list = getJdbcTemplate().query("select * from account whereid = ? ", new AccountRowMapper(), id);
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public Account findAccountByName(String name) {
        //調(diào)用繼承自父類的getJdbcTemplate()方法獲得JdbcTemplate對象
        List<Account> accounts = getJdbcTemplate().query("select * from account wherename = ? ", new BeanPropertyRowMapper<Account>(Account.class), name);
        if (accounts.isEmpty()) {
            return null;
        } else if (accounts.size() > 1) {
            throw new RuntimeException("結(jié)果集不唯一,不是只有一個賬戶對象");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        //調(diào)用繼承自父類的getJdbcTemplate()方法獲得JdbcTemplate對象
        getJdbcTemplate().update("update account set money = ? where id = ? ", account.getMoney(), account.getId());
    }
}

但是這種配置方法存在一個問題: 因為我們不能修改JdbcDaoSupport類的源代碼,DAO層的配置就只能基于xml配置,而不再可以基于注解配置了.

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容