Spring(六)---Spring中的JdbcTemplate

一、概述

Spring中的JdbcTemplate對原始Jdbc API進行了封裝,Spring對數據庫操作需求提供了很好的支持,並在原始JDBC基礎上,構建了一個抽象層,提供了許多使用JDBC的模板和驅動模塊,爲Spring應用操作關係數據庫提供了更大的便利。所以會使用Spring中的Jdbc是很有必要的。

二、快速入門

1.導入jar包
 		<!--Spring的jar包-->
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
		<!--Spring JdbcTemplate的jar包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
		<!--Spring事務控制的jar包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
		<!--mysql的jar包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
2.編寫Spring的配置文件
  1. 導入約束
  2. 配置數據源,配置數據源,可以有多種選擇,使用C3P0的數據源或者使用spring的內置數據源。
<?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">

    <!--將Dao交給Spring的ioc容器管理-->
    <bean id="accountDao" class="com.SpringDemo4.dao.impl.AccountDaoImpl"></bean>

    <!--將Spring的jdbcTemplate交給Spring的ioc容器管理-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <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>
        <property name="url" value="jdbc:mysql:///user"></property>
        <property name="username" value="root"></property>
        <property name="password" value="213213"></property>
    </bean>
</beans>
3.基本使用
    @Test
    public void testInsert(){
        //獲取ioc容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //獲取jdbcTemplate對象
        JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);
        //執行操作
        jt.execute("insert into account values(3,'wangwu', 1000)");
    }

在這裏插入圖片描述

三、增刪改查的操作

1.保存操作
     //獲取ioc容器
	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
	//獲取jdbcTemplate對象
	JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);
	//執行操作
	jt.update("insert into account(name, money) values('zhaoliu', 1000)");
2.更新操作
 //獲取ioc容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//獲取jdbcTemplate對象
JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);
//執行操作
 jt.update("update account set money = ? where id = ?",500, 2);
3.刪除操作
 //獲取ioc容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//獲取jdbcTemplate對象
JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);
//執行操作
 jt.update("delete from account where id = ?",2);
4.查詢所有操作

查詢操作和其他操作不同的是,需要定義將查詢出來的數據封裝到哪裏,有兩種方式,一種是自定義封裝類繼承RoMapper,另外一種是直接使用Spring的JdbcTemplate提供的封裝類

/**
 * author by four and ten
 * create by 2020/4/6 15:02
 */
public class test {
    @Test
    public void testInsert(){
        //獲取ioc容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //獲取jdbcTemplate對象
        JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);
        //查詢所有
        List<Account> accounts = jt.query("select * from account", new AccountRoMapper());
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
}
//自定義封裝類,實現RowMapper接口
class AccountRoMapper implements RowMapper<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;
    }

}

JdbcTemplate也封裝了一個類,可以供我們直接使用BeanPropertyRowMapper

@Test
    public void testInsert(){
        //獲取ioc容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //獲取jdbcTemplate對象
        JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);
        //查詢所有
        List<Account> accounts = jt.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
5.查詢一個

查詢一個往往使用查詢所有的操作然後返回一個list集合,然後取一個即可

@Test
    public void testInsert(){
        //獲取ioc容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //獲取jdbcTemplate對象
        JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);
        //查詢所有
        List<Account> accounts = jt.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),3);
        System.out.println(accounts.isEmpty() ? "沒有結果" : accounts.get(0));
    }
6.查詢返回一行一列,使用聚合函數
@Test
    public void testInsert(){
        //獲取ioc容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //獲取jdbcTemplate對象
        JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);
        //查詢所有
        Integer total = jt.queryForObject("select count(id) from account", Integer.class);
        System.out.println(total);
    }

四、在dao中使用JdbcTemplate

在dao中使用jdbcTemplate有兩種方式,一種是常規的方式,但是當dao比較多時,有很多的重複代碼,爲了解決這個問題,jdbcTemplate提供了一個JdbcDaoSupport類,讓dao直接繼承這個類,可以減少這些重複性的代碼。

1.編寫dao接口

爲了方便就寫一個方法

public interface IAccountDao {

    /**
     * 根據Id查詢賬戶
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);
}
2.第一種方法使用注入的方式

/**
 * 賬戶的持久層實現類
 */
@Repository
public class AccountDaoImpl2 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);
    }

}

當然在bean.xml配置文件中肯定要將JdbcTemplate交給Spring來管理。在這裏中重複代碼便是set方法,當然解決這個問題有2種方式解決,可以使用註解,也可以使用spring提供的類JdbcDaoSupport。

3.第2種方法
/**
 * 賬戶的持久層實現類
 */
public class AccountDaoImpl 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);
    }
    
}

使用這種方式只需要在bean.xml中配置數據源即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章