java框架之Spring(3)-JDBC模板使用&事務管理

下面內容使用到的 jar 包下載html

JDBC模板使用

入門

一、導包,如要導入 Spring 的基本開發包、數據庫驅動包、Spring 提供的 JDBC 模板包,以下:java

二、測試:mysql

@Test
public void test(){
    // 建立鏈接池對象
    DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
    driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
    driverManagerDataSource.setUrl("jdbc:mysql:///test");
    driverManagerDataSource.setUsername("root");
    driverManagerDataSource.setPassword("root");
    // 建立 JDBC 模板對象
    JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);
    // 經過模板對象操做數據庫
    jdbcTemplate.update("insert into user values(null,?,?)", "bob", 123);
}

將模板交給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">
    <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///test"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>
applicationContext.xml
package com.zze.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void test() {
        jdbcTemplate.update("update user set password=? where username=?", "345", "bob");
    }

}
test

使用第三方鏈接池

DBCP配置

額外導入 jar 包:spring

配置:sql

<?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">
    <!--DBCP 配置-->
    <bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///test"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

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

C3P0配置

額外導入 jar 包:數據庫

配置:express

<?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">
    <!--C3P0鏈接池配置-->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///test"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>

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

抽取JDBC配置到屬性文件

有以下屬性文件:apache

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test
jdbc.username=root
jdbc.password=root
jdbc.properties

方式一:編程

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:jdbc.properties"/>
</bean>

方式二:app

<context:property-placeholder location="classpath:jdbc.properties"/>

接下來就能夠經過以下方式引用到屬性文件中的屬性,例:

<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driverClass}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

CRUD操做

package com.zze.test;

import com.zze.bean.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 保存
     */
    @Test
    public void test1() {
        jdbcTemplate.update("insert into user values (null,?,?)", "bob", "123");
    }

    /**
     * 更新
     */
    @Test
    public void test2() {
        jdbcTemplate.update("update user set password=? where username=?", "346", "bob");
    }

    /**
     * 刪除
     */
    @Test
    public void test3() {
        jdbcTemplate.update("delete from user where username=?", "bob");
    }

    /**
     * 查詢首行首列
     */
    @Test
    public void test4() {
        Integer integer = jdbcTemplate.queryForObject("select COUNT(1) from user", Integer.class);
        System.out.println(integer);
    }

    /**
     * 查詢一條數據封裝到單個對象
     */
    @Test
    public void test5() {
        User user = jdbcTemplate.queryForObject("select * from user where username=?", new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                return user;
            }
        }, "bob");
        System.out.println(user);
    }

    /**
     * 查詢多條記錄封裝到集合
     */
    @Test
    public void test6() {
        List<User> userList = jdbcTemplate.query("select * from user", new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                return user;
            }
        });
        System.out.println(userList);
    }

}

事務管理

事務回顧

參見【數據庫事務瞭解一下】。

Spring事務管理API

  • PlatformTransactionManager:平臺事務管理器

    接口,是 Spring 用於管理事務真正的對象。

    DataSourceTransactionManager:底層使用JDBC管理事務。

    HibernateTransactionManager:底層使用Hibernate管理事務。

  • TransactionDefinition:事務定義信息

    用於定義事務的相關的信息,隔離級別、超時信息、傳播行爲、是否只讀。

  • TransactionStatus:事務的狀態

    用於記錄在事務管理過程當中,事務的狀態的對象。

上述API之間的關係:

       Spring進行事務管理的時候,首先平臺事務管理器根據事務定義信息進行事務的管理,在事務管理過程當中,產生各類狀態,將這些狀態的信息記錄到事務狀態的對象中。

事務的傳播行爲

Spring 中提供了七種事務的傳播行爲,可分爲以下三類:

  • 保證多個操做在同一個事務中:

    PROPAGATION_REQUIRED :默認值,若是A中有事務,使用A中的事務,若是A沒有,建立一個新的事務,將操做包含進來

    PROPAGATION_SUPPORTS :支持事務,若是A中有事務,使用A中的事務。若是A沒有事務,不使用事務。

    PROPAGATION_MANDATORY :若是A中有事務,使用A中的事務。若是A沒有事務,拋出異常。

  • 保證多個操做不在同一個事務中:

    PROPAGATION_REQUIRES_NEW :若是A中有事務,將A的事務掛起(暫停),建立新事務,只包含自身操做。若是A中沒有事務,建立一個新事務,包含自身操做。

    PROPAGATION_NOT_SUPPORTED :若是A中有事務,將A的事務掛起。不使用事務管理。

    PROPAGATION_NEVER :若是A中有事務,報異常。

  • 嵌套式事務:

    PROPAGATION_NESTED :嵌套事務,若是A中有事務,按照A的事務執行,執行完成後,設置一個保存點,執行B中的操做,若是沒有異常,執行經過,若是有異常,能夠選擇回滾到最初始位置,也能夠回滾到保存點。

搭建Spring的事務管理的環境

準備

建立 account 表並初始化以下數據:

下面代碼模擬一個轉帳場景:

package com.zze.dao;

public interface AccountDao {
    /**
     * 轉出
     * @param username 轉出帳戶的用戶名
     * @param money 轉出金額
     */
    void outMoney(String username,Double money);

    /**
     * 轉入
     * @param username 轉入帳戶的用戶名
     * @param money 轉入金額
     */
    void inMoney(String username, Double money);
}
com.zze.dao.AccountDao
package com.zze.dao.impl;

import com.zze.dao.AccountDao;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
    @Override
    public void outMoney(String username, Double money) {
        this.getJdbcTemplate().update("update account set money=money-? where username=?", money, username);
    }

    @Override
    public void inMoney(String username, Double money) {
        this.getJdbcTemplate().update("update account set money=money+? where username=?", money, username);
    }
}
com.zze.dao.impl.AccountDaoImpl
package com.zze.service;

public interface AccountService {
    /**
     * 轉帳
     * @param usernameFrom 轉帳來源帳戶
     * @param usernameTo 轉帳目標帳戶
     * @param money 轉帳金額
     */
    void transfer(String usernameFrom,String usernameTo,Double money);
}
com.zze.service.AccountService
package com.zze.service.impl;

import com.zze.dao.AccountDao;
import com.zze.service.AccountService;

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void transfer(String usernameFrom, String usernameTo, Double money) {
        accountDao.outMoney(usernameFrom, money);
        accountDao.inMoney(usernameTo,money);
    }
}
com.zze.service.impl.AccountServiceImpl
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test
jdbc.username=root
jdbc.password=root
jdbc.properties
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

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

    <bean name="accountDao" class="com.zze.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
        <!--<property name="jdbcTemplate" ref="jdbcTemplate"/>-->
    </bean>

    <bean name="accountService" class="com.zze.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
</beans>
applicationContext.xml
package com.zze.test;

import com.zze.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
    @Resource(name = "accountService")
    private AccountService accountService;
    @Test
    public void test(){
        // zhangsan 給 lisi 轉帳 100
        accountService.transfer("zhangsan","lisi",100d);
    }
}
執行結果以下:

test

編程式事務管理

一、修改配置:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置 C3p0 鏈接池-->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--配置事務管理器-->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--配置事務的管理的模板類-->
    <bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"/>
    </bean>

    <bean name="accountDao" class="com.zze.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean name="accountService" class="com.zze.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
        <!--注入事務管理模板-->
        <property name="transactionTemplate" ref="transactionTemplate"/>
    </bean>
</beans>
applicationContext.xml

二、修改代碼模擬異常並使用事務:

package com.zze.service.impl;

import com.zze.dao.AccountDao;
import com.zze.service.AccountService;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;
    private TransactionTemplate transactionTemplate;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    @Override
    public void transfer(String usernameFrom, String usernameTo, Double money) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                accountDao.outMoney(usernameFrom, money);
                // 模擬過程當中異常
                int i = 1 / 0;
                accountDao.inMoney(usernameTo, money);
            }
        });
    }
}
com.zze.service.impl.AccountServiceImpl

三、測試:

package com.zze.test;

import com.zze.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
    @Resource(name = "accountService")
    private AccountService accountService;
    @Test
    public void test(){
        // zhangsan 給 lisi 轉帳 100
        accountService.transfer("zhangsan","lisi",100d);

        // 此時表數據將不會發生變化
    }
}
test

聲明式事務管理-XML

一、修改配置:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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/context http://www.springframework.org/schema/context/spring-context.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">
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置 C3p0 鏈接池-->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--配置事務管理器-->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--配置事務的通知/加強-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--事務管理規則-->
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="find*" read-only="true"/>
            <!--
            name : 匹配方法名
            read-only : 爲 true 時表示只作只讀操做
            propagation : 事務的傳播行爲
            timeout : 事務過時時間,爲 -1 時不會過時
            isolation : 事務的隔離級別
            -->
            <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" timeout="-1"/>
        </tx:attributes>
    </tx:advice>

    <!--AOP 配置-->
    <aop:config>
        <aop:pointcut id="pc_account" expression="execution(* com.zze.service.AccountService.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pc_account"/>
    </aop:config>

    <bean name="accountDao" class="com.zze.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean name="accountService" class="com.zze.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
</beans>
applicationContext.xml

二、修改代碼模擬異常:

package com.zze.service.impl;

import com.zze.dao.AccountDao;
import com.zze.service.AccountService;

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void transfer(String usernameFrom, String usernameTo, Double money) {
        accountDao.outMoney(usernameFrom, money);
        // 模擬過程當中異常
        int i = 1 / 0;
        accountDao.inMoney(usernameTo, money);
    }
}
com.zze.service.impl.AccountServiceImpl

三、測試:

package com.zze.test;

import com.zze.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
    @Resource(name = "accountService")
    private AccountService accountService;
    @Test
    public void test(){
        // zhangsan 給 lisi 轉帳 100
        accountService.transfer("zhangsan","lisi",100d);

        // 此時表數據將不會發生變化
    }
}
test

聲明式事務管理-註解

一、修改配置:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置 C3p0 鏈接池-->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--配置事務管理器-->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--開啓註解事務-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean name="accountDao" class="com.zze.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean name="accountService" class="com.zze.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
</beans>
applicationContext.xml

二、修改代碼模擬異常並添加事務註解:

package com.zze.service.impl;

import com.zze.dao.AccountDao;
import com.zze.service.AccountService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

// 業務類上添加註解使用事務
@Transactional(isolation=Isolation.DEFAULT,propagation = Propagation.REQUIRED)
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void transfer(String usernameFrom, String usernameTo, Double money) {
        accountDao.outMoney(usernameFrom, money);
        // 模擬過程當中異常
        int i = 1 / 0;
        accountDao.inMoney(usernameTo, money);
    }
}
com.zze.service.impl.AccountServiceImpl

三、測試:

package com.zze.test;

import com.zze.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
    @Resource(name = "accountService")
    private AccountService accountService;
    @Test
    public void test(){
        // zhangsan 給 lisi 轉帳 100
        accountService.transfer("zhangsan","lisi",100d);

        // 此時表數據將不會發生變化
    }
}
test
相關文章
相關標籤/搜索