Spring事务源码详解

Spring事务源码详解,第1张

一. 简介 事务:

事务是逻辑上的一组 *** 作,要么都执行,要么都不执行,关于事务的基本知识可以看我的这篇文章:事务的基础知识

Spring事务:

Spring 支持两种方式的事务管理:编程式事务管理、声明式事务管理

  • 编程式事务管理:通过 TransactionTemplate或者TransactionManager手动管理事务,使用较少,但是可以让我们精准控制事务粒度,实现精确的细粒度事务控制
  • 声明式事务管理:通过 AOP 实现,@Transactional注解是最常用的声明式事务使用
二.通过例子来学习

maven依赖:

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-contextartifactId>
    <version>5.3.8version>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-txartifactId>
    <version>5.3.8version>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-jdbcartifactId>
    <version>5.3.8version>
dependency>
<dependency>
     <groupId>mysqlgroupId>
     <artifactId>mysql-connector-javaartifactId>
     <version>8.0.25version>
 dependency>
 <dependency>
     <groupId>org.aspectjgroupId>
     <artifactId>aspectjweaverartifactId>
     <version>1.6.9version>
 dependency>

实体类:

public class Book {

    private int bookId;

    private String bookName;

    public Book(int bookId, String bookName) {
        this.bookId = bookId;
        this.bookName = bookName;
    }

    public Book() {
    }

    public int getBookId() {
        return bookId;
    }

    public void setBookId(int bookId) {
        this.bookId = bookId;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bookId=" + bookId +
                ", bookName='" + bookName + '\'' +
                '}';
    }
}

Dao接口类:

import com.jingchuan.transaction.model.Book;

public interface LibraryDao {
	/**
	 * 取得书
	 * @param name
	 * @return book
	 */
	public Book getBook(String name);
	/**
	 * 增加书
     * @param book
	 */
	public void addBook(Book book);
	/**
	 * 删除书
     * @param name
	 */
	public void deleteBook(String name);
 
}

Dao实现类:

import java.sql.ResultSet;
import java.sql.SQLException;

import com.jingchuan.transaction.model.Book;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class LibraryDaoImpl implements LibraryDao {

    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

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

    @Override
    public Book getBook(String name) {
        String sql = "SELECT * FROM book WHERE bookname=?";
        Book mBook = (Book) jdbcTemplate.queryForObject(sql, new Object[]{name}, new RowMapper<Object>() {
            @Override
            public Object mapRow(ResultSet arg0, int arg1) throws SQLException {
                Book book = new Book();
                book.setBookId(arg0.getInt("bookId"));
                book.setBookName(arg0.getString("bookName"));
                return book;
            }
        });
        return mBook;
    }

    @Override
    public void addBook(Book book) {
        String sql = "INSERT INTO book VALUES(?,?)";
        jdbcTemplate.update(sql, book.getBookId(), book.getBookName());
//        jdbcTemplate.update(sql, book.getBookId(), book.getBookName());
    }

    @Override
    public void deleteBook(String name) {
        String sql = "DELETE FROM book WHERE bookname=?";
        jdbcTemplate.update(sql, name);
    }

}

xml配置:


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    bean>
    
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    bean>
    
    <bean id="txManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>
    
    <bean id="libraryFactory" class="com.jingchuan.transaction.dao.LibraryDaoImpl"
          p:jdbcTemplate-ref="jdbcTemplate" />

    
    <aop:config>
        
        <aop:pointcut id="serviceMethod"
                      expression="execution(* com.jingchuan.transaction.dao.LibraryDaoImpl.*(..))" />
        
        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
    aop:config>

    
    <tx:advice id="txAdvice" transaction-manager="txManager">
        
        <tx:attributes>
            <tx:method name="get*" read-only="true" />
            <tx:method name="add*" rollback-for="Exception" propagation="REQUIRED"/>
            <tx:method name="del*" />
        tx:attributes>
    tx:advice>
beans>

测试类:

import com.jingchuan.transaction.dao.LibraryDao;
import com.jingchuan.transaction.model.Book;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestTransaction {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:transaction.xml");
        Book book1 = new Book(1, "西游记");
        Book book2 = new Book(2, "红楼梦");
        Book book3 = new Book(3, "金瓶梅");
        Book book4 = new Book(4, "三国演义");
        Book book5 = new Book(5, "水浒传");
        LibraryDao libraryDaoImpl = (LibraryDao) ctx.getBean("libraryFactory");
        libraryDaoImpl.addBook(book2);
        System.out.println(libraryDaoImpl.getBook("西游记"));
    }

}

需要自己创建一个数据库并创建Book表,bookId和bookName两个字段:

CREATE TABLE `book` (
  `bookId` int(11) NOT NULL,
  `bookName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`bookId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
三. 跟着例子看源码

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/786208.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-05
下一篇 2022-05-05

发表评论

登录后才能评论

评论列表(0条)

保存