Spring5(13)- JdbcTemplate

1 JdbcTemplate 概述

  • 它是spring框架中提供的一個對象,是對原始Jdbc API對象的簡單封裝。

spring框架爲我們提供了很多的操作模板類。

  • 操作關係型數據的: JdbcTemplate HibernateTemplate
  • 操作nosql數據庫的: RedisTemplate
  • 操作消息隊列的: JmsTemplate
    在這裏插入圖片描述

2 入門

導入依賴

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring-version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring-version}</version>
    </dependency>

2.1 案例

/**
 * JdbcTemplate的最基本用法
 */
public class JdbcTemplateDemo1 {
    public static void main(String[] args) {

        // 準備數據源,spring內置的數據源
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/spring5?useSSL=false");
        ds.setUsername("root");
        ds.setPassword("root");



        // 1. 創建 JdbcTemplate 對象
        JdbcTemplate jt = new JdbcTemplate();
        jt.setDataSource(ds);

        // 2.執行操作
        jt.execute("insert into account(name,money) values ('Ken',1111)");

    }
}

2.2 使用 IOC 配置 JdbcTemplate

  • bean.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:context="http://www.springframework.org/schema/context"
       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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.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="com.mchange.v2.c3p0.DriverManagerDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring5?useSSL=false"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

</beans>
public class JdbcTemplateDemo2 {
    public static void main(String[] args) {
        // 1. 獲取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.獲取對象
        JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
        //3.執行操作
        jt.execute("insert into account(name,money) values('ZZZ',1000)");
    }
}

3 JdbcTemplate 的CRUD

3.1 案例1

public class JdbcTemplateDemo3 {
    public static void main(String[] args) {
        // 1. 獲取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.獲取對象
        JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
        //3.執行操作

        // 保存
        //jt.update("insert into account(name,money) values (?,?)","AAA",1111f);

        // 更新
        //jt.update("update account set name=?,money=? where id=?", "ABB", 2222f, 5);

        //刪除
        //jt.update("delete from account where id=? ",6);

        // 查詢所有
        List<Account> accounts = jt.query("select * from account where money > ?", new AccountRowMapper(), 100f);

        for (Account account : accounts) {
            System.out.println(account);
        }

    }
}

// 定義 Account 的封裝策略
class AccountRowMapper implements RowMapper<Account> {

    /**
     * 把結果集的數據封裝到Account,然後由 spring 把每個 Account 加到集合中
     *
     * @param rs
     * @param i
     * @return
     * @throws SQLException
     */
    @Override
    public Account mapRow(ResultSet rs, int i) throws SQLException {
        Account account = new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getFloat("money"));
        return account;
    }
}

在這裏插入圖片描述

3.2 案例2

public class JdbcTemplateDemo3 {
    public static void main(String[] args) {
        // 1. 獲取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.獲取對象
        JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
        //3.執行操作

        // 查詢所有
        List<Account> accounts = jt.query("select * from account where money > ?",
                new BeanPropertyRowMapper<Account>(Account.class), 100f);

        for (Account account : accounts) {
            System.out.println(account);
        }

    }
}

  • 查詢一個
  // 查詢一個
        List<Account> accounts = jt.query("select * from account where id= ?",
                new BeanPropertyRowMapper<Account>(Account.class), 1);

// 查詢返回一行一列(使用聚合函數,但是不加 group by 子句)
        Integer count = jt.queryForObject("select count(*) from account where money > ?", Integer.class, 100f);
        System.out.println(count);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章