Spring5 Note 2 - JDBC Template Operation Database, Transaction Operation

Table of contents

JdbcTemplate (concept and preparation) 26

1. What is JdbcTemplate

(1) The Spring framework encapsulates JDBC and uses JdbcTemplate to facilitate database operations

2. Preparation

insert image description here
insert image description here
insert image description here
insert image description here

JdbcTemplate operation database (addition) 28

tables in the database
insert image description here
insert image description here
insert image description here
insert image description here

JdbcTemplate operation database (modification and deletion) 29

insert image description here

JdbcTemplate operates the database (the query returns a value) 29

insert image description here
insert image description here

JdbcTemplate operates the database (query returns objects) 30

insert image description here

JdbcTemplate operates database (query returns collection) 30

insert image description here

JdbcTemplate operation database (batch operation) 30

1. Batch operation: multiple records in the operation table
2. JdbcTemplate realizes batch adding operation
insert image description here
insert image description here
insert image description here

Transaction Operations (Transaction Concept) 32

insert image description here
Note:
Atomicity:
A transaction is an atomic operation consisting of a series of actions. The atomicity of transactions ensures that actions are either fully completed or have no effect at all. (Indivisible, both succeed or both fail)

Consistency: Once a transaction is completed (regardless of whether it succeeds or fails), the system must ensure that the business it models is in a consistent state, rather than partially completed and partially failed. In reality the data should not be corrupted. (The total amount of money remains the same before and after the operation, and the sum is still 200, that is, the total amount before and after the transfer is 200)

Isolation: There may be many transactions processing the same data at the same time, so each transaction should be isolated from other transactions to prevent data corruption. (There will be no impact between them during multi-transaction operations, and there will be no impact if two people operate the same record)

Durability: Once a transaction completes, its results should not be affected no matter what system error occurs, so that it can recover from any system crash. Typically, the results of transactions are written to persistent storage. (The transaction needs to be submitted, and the data in the submitted table has changed)

Transaction operation (building a transaction operation environment) 32

Three layers of javaEE: web, Service, Dao
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

Additional code:

xml configuration file: bean1.xm

<?xml version="1.0" encoding="UTF-8"?>
<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: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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 组件扫描 -->
    <context:component-scan base-package="com.atguigu"></context:component-scan>

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql:///user_db" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </bean>

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

    <!--创建事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

Service code:

package com.atguigu.spring5.service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Transactional(readOnly = false,timeout = -1,propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)
public class UserService {
    
    

    //注入dao
    @Autowired
    private UserDao userDao;

    //转账的方法
    public void accountMoney() {
    
    
//        try {
    
    
            //第一步 开启事务

            //第二步 进行业务操作
            //lucy少100
            userDao.reduceMoney();

            //模拟异常
            int i = 10/0;

            //mary多100
            userDao.addMoney();

            //第三步 没有发生异常,提交事务
//        }catch(Exception e) {
    
    
            //第四步 出现异常,事务回滚
//        }
    }
}

interface:

package com.atguigu.spring5.dao;

public interface UserDao {
    
    
    //多钱
    public void addMoney();
    //少钱
    public void reduceMoney();
}

interface implementation class

package com.atguigu.spring5.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    
    

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //lucy转账100给mary
    //少钱
    @Override
    public void reduceMoney() {
    
    
        String sql = "update t_account set money=money-? where username=?";
        jdbcTemplate.update(sql,100,"lucy");
    }

    //多钱
    @Override
    public void addMoney() {
    
    
        String sql = "update t_account set money=money+? where username=?";
        jdbcTemplate.update(sql,100,"mary");
    }
}

test:

 @Test
    public void testAccount() {
    
    

        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.accountMoney();
    }

Transaction Operation (Introduction to Spring Transaction Management) 35

In development, it is generally written to the Service layer, using declarative transaction management, based on annotations, and using aop.
For example, if you ask where aop is used in the project, just answer the transaction
insert image description here

Transaction operation (annotation declarative transaction management) 35

insert image description here
insert image description here

Transaction operation (declarative transaction management parameter configuration) 36

formal content

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

to add on

1. Add the annotation @Transactional on the service class, and you can configure transaction-related parameters in this annotation

2. Propagation: Transaction propagation behavior, that is, when a transaction method is called by another transaction method, how does this transaction method proceed

  • requied
    insert image description here
  • required-new
    insert image description here
  • supports

insert image description here

3. ioslation: transaction isolation level

There are three reading problems: dirty read, non-repeatable read, phantom (phantom) read

Mysql default is REPEATABLE_READ repeatable read

4. timeout: timeout

(1) The transaction needs to be submitted within a certain period of time. If it is not submitted, it will be rolled back.
(2) The default value is -1, and the setting time is calculated in seconds

@Service
@Transactional(readOnly = false,timeout = -1,propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)
public class UserService {
    
    

5. readOnly: Whether to read only

(1) Read: query operation, write: add, modify, and delete operations
(2) The default value of readOnly is false, indicating that it can be queried, and can add, modify, and delete operations
(3) Set the value of readOnly to true, after setting it to true, only query

6. rollbackFor: rollback

(1) Set which exceptions occur for transaction rollback

7. noRollbackFor: no rollback

(1) Set which exceptions do not perform transaction rollback

Transaction operations (XML declarative transaction management) are not important, in practice, use annotations on page 38

insert image description here
insert image description here

Transaction operations (fully annotated declarative transaction management)

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/m0_50736744/article/details/126197755