Spring框架學習筆記03

1.Spring整合JDBC

(1)spring提供了很多模板整合Dao技術

這裏寫圖片描述

(2)spring中提供了一個可以操作數據庫的對象.對象封裝了jdbc技術.

JDBCTemplate => JDBC模板對象
與DBUtils中的QueryRunner非常相似.
@Test
public void fun1() throws Exception{
    //0.準備連接池
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    dataSource.setDriverClass("com.mysql.jdbc.Driver");
    dataSource.setJdbcUrl("jdbc:mysql:///test?useUnicode=true&characterEncoding=UTF-8");
    dataSource.setUser("root");
    dataSource.setPassword("root");
    //1.創建jdbc模板對象
    JdbcTemplate jt = new JdbcTemplate(dataSource);
    //2.寫sql
    String sql = "insert into t_user values(null,'王小二')";
    jt.update(sql);
}

(3)步驟

1.導包

這裏寫圖片描述
2.準備數據庫
這裏寫圖片描述
3.書寫DAO

package cn.itcast.a_jdbctemplete;

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

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import cn.itcast.bean.User;

//使用Jdbc模板實現增刪改查
public class UserDaoImpl extends JdbcDaoSupport implements UserDao{

    //增加
    public void save(User user) {
        String sql = "insert into t_user values(null,?)";
        super.getJdbcTemplate().update(sql, user.getName());
    }

    //刪除
    public void delete(Integer id) {
        String sql = "delete from t_user where id=?";
        super.getJdbcTemplate().update(sql, id);
    }

    //修改
    public void update(User user) {
        String sql = "update t_user set name=? where id=?";
        super.getJdbcTemplate().update(sql,user.getName(),user.getId());
    }

    //根據用戶Id進行查詢
    public User getById(Integer id) {
        String sql = "select * from t_user where id=?";
        return super.getJdbcTemplate().queryForObject(sql, new RowMapper<User>(){

            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }

        }, id);
    }

    //查詢用戶總數量
    public int getTotal() {
        String sql = "select count(*) from t_user";
        Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);
        return count;
    }

    //查詢用戶集合
    public List<User> getAll() {
        String sql = "select * from t_user";
        List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>(){

            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }

        });
        return list;
    }

}
4.spring配置
依賴關係

這裏寫圖片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">

<!-- 指定spring讀取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"  />

<!-- 1.將連接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
</bean>


<!-- 2.將JDBCTemplate放入spring容器 -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>

<!-- 3.將UserDao放入spring容器 -->
<bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" >
    <!-- <property name="jt" ref="jdbcTemplate" ></property> -->
    <property name="dataSource" ref="dataSource" ></property>
</bean>

</beans>
5.測試
package cn.itcast.a_jdbctemplete;

import java.util.List;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.itcast.bean.User;

import com.mchange.v2.c3p0.ComboPooledDataSource;

//演示jdbc模板
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {

    @Resource(name="userDao")
    private UserDao ud;

    @Test
    public void fun2(){
        User user = new User(null, "李斯");
        ud.save(user);
    }

    @Test
    public void fun3(){
        User user = new User();
        user.setId(12);
        user.setName("黃老九");
        ud.update(user);
    }

    @Test
    public void fun4(){
        ud.delete(10);
    }

    @Test
    public void fun5(){
        User user = ud.getById(6);
        System.out.println(user);
    }

    @Test
    public void fun6(){
        int count = ud.getTotal();
        System.out.println(count);
    }

    @Test
    public void fun7(){
        List<User> list = ud.getAll();
        for (User user : list) {
            System.out.println(user);
        }
    }
}

(4)進階內容

1.JDBCDaoSupport
public class UserDaoImpl extends JdbcDaoSupport implements UserDao{}

這裏寫圖片描述

<!-- 3.將userDao放入spring容器管理 -->
<bean name="userDao" class="cn.itcast.a_jdbctemplete.UserDaoImpl">
    <!-- <property name="jt" ref="jdbcTemplete"></property> -->
    <property name="dataSource" ref="dataSource"></property>
</bean>
2.讀取外部的Properties配置
#注意加前綴db.properties
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/test?useUnicode=true&amp&characterEncoding=utf8
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root
<!-- 指定spring讀取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"  />

<!-- 1.將連接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
</bean>

2.Spring中AOP事務

(1)事務

1.事務特性:acid
2.事務併發問題
    髒讀
    不可重複讀
    幻讀
3.事務的隔離級別
    1:讀未提交
    2:讀已提交
    4:可重複讀
    8:串行化

(2)spring封裝了事務管理代碼

1.事務操作
    打開事務
    提交事務
    回滾事務
2.事務操作對象
  a>因爲在不同平臺,操作事務的代碼各不相同.spring提供了一個接口
  b>PlatformTransactionManager 接口
      DataSourceTransactionManager
      HibernateTransitionmanager
      注意:在spring中玩事務管理.最爲核心的對象就是TransactionManager對象
  c>spring管理事務的屬性介紹
      事務的隔離級別
        1:讀未提交
        2:讀已提交
        4:可重複讀
        8:串行化
      是否只讀
        true 只讀
        false 可操作
      事務的傳播行爲

這裏寫圖片描述

(3)spring管理事務方式

1.編碼式
    a.將核心事務管理器配置到spring容器
<!-- 事務核心管理器,封裝了所有事務操作,依賴於連接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>
    b.配置TransactionTemplate模板
<!-- 事務模板對象 -->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="transactionManager" ref="transactionManager"></property>
</bean>
    c.將事務模板注入Service
<!-- 3.service -->
<!-- 將事務模板對象注入到service中 -->
<bean name="accountService" class="cn.itcast.dao.AccountServiceImpl">
    <property name="accountDao" ref="accountDao"></property>
    <property name="transactionTemplate" ref="transactionTemplate"></property>
</bean>
    d.在Service中調用模板
    public void transfer(Integer from,Integer to,Double money) {

            //減錢
            accountDao.descreaseMoney(from, money);

            //int a = 1/0;

            //加錢
            accountDao.increaseMoney(to, money);
        }
2.xml配置(aop)
  a.導包
  b.導入新的約束(tx)
    beans: 最基本
    context:讀取properties配置
    aop:配置aop
    tx:配置事務通知
  c.配置通知
<!-- 配置事務通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <!--以方法爲 單位,指定方法應用什麼事務屬性 
            isolation:隔離級別
            propagation:傳播行爲
            read-only:是否只讀
         -->
         <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
         <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
         <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
         <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
         <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
         <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
         <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
         <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
        <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
    </tx:attributes>
</tx:advice>
  d.配置將通知織入目標
<!-- 配置織入 -->
<aop:config>
    <!-- 配置切點表達式 -->
    <aop:pointcut expression="execution(* cn.itcast.dao.*ServiceImpl.*(..))" id="txpc"/>
    <!-- 配置切面
         通知advice-ref  +  切點pointcut-ref -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txpc"/>
</aop:config>
3.註解配置(aop)
 a.導包
 b.導入新的約束(tx)
 c.開啓註解管理事務
<!-- 開啓使用註解管理事務 -->
<tx:annotation-driven/>
 d.使用註解
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
public class AccountServiceImpl implements AccountService{
    @Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)
    public void transfer(Integer from,Integer to,Double money) {

這裏寫圖片描述

發佈了63 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章