Spring黑馬:JdbcTemplate對象(連接數據庫JDBC)

1. JdbcTemplate對象

  • JdbcTemplated是Spring提供的一個連接數據庫的org.springframework.jdbc.core.JdbcTemplate
  • dbutils.QueryRunner是dbutils包提供的一個連接數據庫
  • 兩者類似。

2. 由JdbcTemplate對象自己提供的數據庫

  • JdbcTemplate中的DriverManagerDataSource可以準備數據源;
  • execute方法執行SQL語句,直接把參數值寫死,不用佔位符?。
JdbcTemplateDemo1
package com.jh.jdbctemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**JdbcTemplate的最基本用法*/
public class JdbcTemplateDemo1 {
    public static void main(String[] args) {
        //準備數據源
        DriverManagerDataSource ds=new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/maven?serverTimezone=GMT%2B8");
        ds.setUsername("root");
        ds.setPassword("jh7851192");
        //1.創建JdbcTemplate對象
        JdbcTemplate jt = new JdbcTemplate();
        //給jt設置數據源
        jt.setDataSource(ds);
        //2.執行操作
        jt.execute("insert into account(name,money)values ('ccc',1200)");
    }
}

3.JdbcTemplate採用XML配置的方法配置數據庫

不用像JdbcTemplateDemo1一樣把數據庫寫死

JdbcTemplateDemo2
package com.jh.jdbctemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**JdbcTemplate的最基本用法
 * 採用XML配置的方法配置數據源,不用像JdbcTemplateDemo1一樣把數據庫寫死
 * */
public class JdbcTemplateDemo2 {
    public static void main(String[] args) {
        //1.獲取容器
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.獲取bean對象JdbcTemplate
        JdbcTemplate jt=ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //3.執行操作
        //execute 沒有佔位符?,直接寫參數值
        jt.execute("insert into account(name,money)values ('ddd',2200)");
    }
}

bean.xml

  • 這裏也是配置數據源class="org.springframework.jdbc.datasource.DriverManagerDataSource
  • 只是把DriverManagerDataSource寫到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.xsd">

    <!-- 配置賬戶的持久層-->
    <bean id="accountDao" class="com.jh.dao.impl.AccountDaoImpl">
        <!--注入JdbcTemplate對象-->
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
        <!--<property name="dataSource" ref="dataSource"></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.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/maven?serverTimezone=GMT%2B8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="jh7851192"></property>
    </bean>
</beans>

4. JdbcTemplate對象 CRUD操作(數據庫xml已配置)

  • 執行操作(這裏寫佔位符? 和QueryRunner(query,update)一樣,但是和execute方法不一樣)
  • Spring提供一個BeanPropertyRowMapper,類似於dbutils.QueryRunner中的BeanListHandler,BeanHandler
JdbcTemplateDemo3
public class JdbcTemplateDemo3 {
    public static void main(String[] args) {
        //1.獲取容器
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.獲取bean對象JdbcTemplate
        JdbcTemplate jt=ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //3.執行操作(這裏寫佔位符? 和QueryRunner(query,update)一樣,但是和execute方法不一樣)
        /*//保存
        jt.update("insert into account(name,money)values (?,?)","eee",2345f);
        //更新
        jt.update("update account set name=?,money=? where id=?","jh2",2324f,6);
        //刪除
        jt.update("delete from account where id=?",6);*/
        //查詢所有
        //List<Account>accounts = jt.query("select * from account where money > ?",new AccountRowMapper(),1000f);
        /**Spring提供一個BeanPropertyRowMapper,類似於dbutils.QueryRunner中的BeanListHandler,BeanHandler
         * 以後不用自己寫實現類:class AccountRowMapper*/
        /*List<Account>accounts = jt.query("select * from account where money > ?",new BeanPropertyRowMapper<Account>(Account.class),1000f);
        for (Account account:accounts){
            System.out.println(account);
            Account{id=1, name='aaa', money=4566.0}
            Account{id=5, name='jh', money=12213.0}
            Account{id=7, name='ddd', money=2200.0}
        }*/
        //查詢一個
        List<Account> accounts = jt.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1);
        System.out.println(accounts.isEmpty()?"沒有內容":accounts.get(0));
        //Account{id=1, name='aaa', money=4566.0}
        //查詢返回一行一列(使用聚合函數,但不加group by子句)
        Long count = jt.queryForObject("select count(*) from account where money >?", Long.class, 1000f);
        System.out.println(count);//3
    }
}
//這是自己寫的類AccountRowMapper
class AccountRowMapper implements RowMapper<Account>{
    /**
     * 把結果集中的數據封裝到Account中,然後由Spring把每個Account加到集合中
     * */
    @Override
    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
        Account account=new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getFloat("money"));
        return account;
    }
}

5. 將SQL語句寫在持久層

  • 通過獲取IAccountDao的bean對象,已在bean.xml裏逐步注入對象,進行調用,實現數據庫的調用;
  • accountDao—>jdbcTemplate—>dataSource
JdbcTemplateDemo4
public class JdbcTemplateDemo4 {
    public static void main(String[] args) {
        //1.獲取容器
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.獲取bean對象
        IAccountDao accountDao=ac.getBean("accountDao",IAccountDao.class);
        //3.執行操作
        Account account = accountDao.findAccountById(2);
        System.out.println(account);//Account{id=1, name='aaa', money=4566.0}
        account.setMoney(1200f);
        accountDao.updateAccount(account);//下一次就更新爲Account{id=1, name='aaa', money=1230.0}
    }
}

Account

package com.jh.domain;
import java.io.Serializable;
/**賬戶的實體類*/
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 +
                '}';
    }
}

IAccountDao

package com.jh.dao;
import com.jh.domain.Account;
/**持久層*/
public interface IAccountDao {
    //根據id查詢賬戶
    Account findAccountById(Integer accountId);
    //根據名稱查詢賬戶
    Account findAccountByName(String accountName);
    //更新賬戶
    void updateAccount(Account account);
}

SQL語句在持久層實現類寫

package com.jh.dao.impl;
import com.jh.dao.IAccountDao;
import com.jh.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**持久層實現類*/
public class AccountDaoImpl implements IAccountDao {
    private JdbcTemplate jdbcTemplate;

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

    @Override
    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);
    }

    @Override
    public Account findAccountByName(String accountName) {
        List<Account> accounts = jdbcTemplate.query("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), accountName);
        if (accounts.isEmpty()){
            return null;
        }if (accounts.size()>1){
            throw new RuntimeException("結果集不唯一");
        }
        return accounts.get(0);
    }

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

抽取重複代碼:可以省略private JdbcTemplate jdbcTemplate;和set方法
extends JdbcDaoSupport

package com.jh.dao.impl;
import com.jh.dao.IAccountDao;
import com.jh.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;
/**持久層實現類
 *抽取重複代碼:可以省略private JdbcTemplate jdbcTemplate;和set方法
 * */
public class AccountDaoImpl2 extends JdbcDaoSupport implements IAccountDao {
    @Override
    public Account findAccountById(Integer accountId) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where id=?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
        return accounts.isEmpty()?null:accounts.get(0);
    }

    @Override
    public Account findAccountByName(String accountName) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), accountName);
        if (accounts.isEmpty()){
            return null;
        }if (accounts.size()>1){
            throw new RuntimeException("結果集不唯一");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章