【Spring】Spring複習之JDBC

如果對此文感興趣,可以繼續看下一篇博文,持續更新,新手學習,有問題歡迎指正:
https://blog.csdn.net/renjingjingya0429/article/details/90241005

一、Spring中的JdbcTemplate

1.1 JdbcTemplate概述
它是Spring框架中提供的一個對象,是對原始Jdbc API對象的簡單封裝。Spring框架爲我們提供了很多的操作類模板。
操作關係型數據庫的:

  • JdbcTemplate
  • HibernateTemplate

操作nosql數據庫的:

  • RedisTemplate

操作消息隊列的:

  • JmsTemplate

1.2 Spring 中配置數據源
(1)導入jar包。
(2)編寫Spring 的配置文件。
(3)配置數據源(我們使用的是 Spring 內置的數據源)。
①配置c3p0數據源
在這裏插入圖片描述
導入c3p0的jar包。在 Spring 的配置文件中配置:

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
	<property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property>
	<property name="user" value="root"></property>
</bean>

②配置dbcp數據源
在這裏插入圖片描述
導入dbcp的jar包。在 Spring 的配置文件中配置:

<!-- 配置數據源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url" value="jdbc:mysql:// /spring_day02"></property>
	<property name="username" value="root"></property>
	<property name="password" value="1234"></property>
</bean>

③配置Spring內置的數據源
Spring 框架也爲我們提供了一個內置的數據源,在spring-jdbc-5.0.2.REEASE.jar 包中:
配置如下:

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url" value="jdbc:mysql:///spring_day02"></property>
	<property name="username" value="root"></property>
	<property name="password" value="1234"></property>
</bean>

(4)將數據庫連接的信息配置到屬性文件中。

【定義屬性文件】
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_day02
jdbc.username=root
jdbc.password=123
【引入外部的屬性文件】
一種方式:
 <!-- 引入外部屬性文件: -->
 <bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="location" value="classpath:jdbc.properties"/>
 </bean>
另一種方式:
<context:property-placeholder location="classpath:jdbc.properties"/>

1.3 JdbcTemplate的CRUD操作
(1)前期準備

創建數據庫:
create database spring_day02;
use spring_day02;
創建表:
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;

(2)在Spring 配置文件中配置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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->

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

    <!--配置數據源-->
    <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/mydb"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
</beans>

(3)CRUD操作

/**
 * JDBCTemplate入門用法
 */
public class JdbcTemplateDemo3 {
    public static void main(String[] args) {
        //1.獲取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根據id獲取jdbcTemplate對象
        JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
        //3.執行操作
        //(1)保存
        jt.update("insert into account(name,money) values('楊霞',100)");
        //(2)更新
//        jt.update("update account set money = ? where name = ?",222,"save");
        //(3)刪除
//        jt.update("delete from account where name = ?","save");
        //(4)查詢所有
//        List<Account> Accounts = jt.query("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class),"任靜");
//        for (Account account : Accounts) {
//            System.out.println(account);
//        }
        //(5)查詢一個
        List<Account> Accounts1 = jt.query("select * from account where name=?", new AccountRowMapper(), "任靜");
        System.out.println(Accounts1.isEmpty() ? "沒有結果" : Accounts1.get(0));
//        (6)查詢返回一行一列:聚合函數的使用(queryForObject()是Spring3.x的新方法)
        Integer count1 = jt.queryForObject("select count(*) from account where money>?", Integer.class, "50");
        Long count2 = jt.queryForObject("select count(*) from account where money>?", Long.class, "50");
        System.out.println(count1);
        System.out.println(count2);
    }
}

class AccountRowMapper implements RowMapper<Account> {

    @Override
    public Account mapRow(ResultSet rs, int i) throws SQLException {
        Account account = new Account();
        account.setName(rs.getString("name"));
        account.setMoney(rs.getFloat("money"));
        return account;
    }
}

1.4 在dao中使用JdbcTemplate

1.4.1 實體類

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

1.4.2 第一種方式:在dao中定義JdbcTemplate(此種方式適合使用註解的方式來配置JdbcTemplate)

/**
 * 賬戶的接口
 */
public interface IAccountDao {
    /**
     * 根據id查詢賬戶信息
     */
    public Account findAccountById(Integer id);

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

    /**
     * 更新賬戶信息
     */
    public void updateAccount(Account account);
}
//此種方式適合使用註解的方式來配置JdbcTemplate
/**
 * 賬戶的持久層實現類
 * 需要給dao注入JdbcTemplate
 */
public class AccountDaoImpl implements IAccountDao {

    private JdbcTemplate jdbcTemplate;

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

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

    @Override
    public Account findAccountByName(String name) {
        List<Account> accounts = jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), name);
        if (accounts.isEmpty()) {//此處不需要判斷list是否爲null,因爲在封裝數據的時候,肯定已經有一個list了
            return null;
        }
        if (accounts.size() > 1) {
            throw new RuntimeException("結果集不唯一,請檢查數據");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        jdbcTemplate.update("update account set money = ? where id = ?",account.getMoney(),account.getId());
    }
}

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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->

    <!--配置dao-->
    <bean id="accountDao" class="com.renjing.dao.impl.AccountDaoImpl">
        <!--注入jdbcTemplate-->
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
    <!--配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置數據源-->
    <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/mydb"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
</beans>

1.4.3 讓dao繼承JdbcDaoSupport

public class JdbcDaoSupport {
    //定義對象
    private JdbcTemplate jdbcTemplate;

    //set方法注入數據
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    //判斷數據源是否爲null,爲null使用數據源創建JdbcTemplate
    public void setDataSource(DataSource dataSource) {
        if (this.jdbcTemplate == null) {
            this.jdbcTemplate = createJdbcTemplate(dataSource);
        }
    }

    //使用數據源創建JdbcTemplate
    private JdbcTemplate createJdbcTemplate(DataSource dataSource) {
        jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }
}
/**
 * 賬戶的持久層實現類
 * 需要繼承JdbcDaoSupport
 */
public class AccountDaoImpl2 extends JdbcDaoSupport implements IAccountDao {

    @Override
    public Account findAccountById(Integer id) {
        List<Account> accounts = getJdbcTemplate().query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), id);
        return accounts.isEmpty()?null:accounts.get(0);
    }

    @Override
    public Account findAccountByName(String name) {
        List<Account> accounts = getJdbcTemplate().query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), name);
        if (accounts.isEmpty()) {//此處不需要判斷list是否爲null,因爲在封裝數據的時候,肯定已經有一個list了
            return null;
        }
        if (accounts.size() > 1) {
            throw new RuntimeException("結果集不唯一,請檢查數據");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        getJdbcTemplate().update("update account set money = ? where id = ?",account.getMoney(),account.getId());
    }
}

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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
        
    <!--配置dao2-->
    <bean id="accountDao2" class="com.renjing.dao.impl.AccountDaoImpl2">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置Spring內置數據源-->
    <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/mydb"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
</beans>
<!--配置dbcp數據源
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>-->
    <!--配置c3p0數據源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mydb"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>

dbcp的jar包:
在這裏插入圖片描述
c3p0的jar包:
在這裏插入圖片描述
注意:

  • 第一種在 Dao 類中定義 JdbcTemplate 的方式,適用於所有配置方式(xml 和註解都可以)。
  • 第二種讓 Dao 繼承 JdbcDaoSupport 的方式,只能用於基於 XML 的方式,註解用不了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章