SSM spring (self study notes)

00Spring

spring:
Layered Java SE/EE application full stack lightweight open source framework
Take IoC (Inverse Of Control) and AOP (Aspect Oriented Programming) as the kernel

spring benefits:
Convenient decoupling and simplified development
AOP programming support
Declarative transaction support
Facilitate program testing
Convenient integration of various excellent frameworks
Reduce the difficulty of using Java EE API
Java source code is a classic learning example

Coupling:
Dependencies between programs (including dependencies between classes and dependencies between methods)

Decoupling: reducing dependencies between programs

In actual development, we should do: compile time does not depend, run time depends

Decoupling idea:
The first step is to use reflection to create objects instead of using the new keyword
The second step is to obtain the fully qualified class name of the object to be created by reading the configuration file


Reflection:
Why does an object need to look in the mirror?

    1. It's possible that this object was passed on by others

    2. There may be no object, only a full class name

Through reflection, you can get the information in this class

Three ways to get Class objects
  1. Get class name by class name class    

  2. Get} object name from object getClass()

  3. Get class by full class name Forname (full class name)

01Spring Bean

core -> xmlns

Bean: in computer English, it means reusable component.
JavaBean: reusable component written in java language.
JavaBean > entity class
It is to create our service and dao objects.

First: we need a configuration file to configure our service and dao
Configuration content: unique id = fully qualified class name (key=value)
The second is to create reflection objects by reading the configured contents in the configuration file

Configuration file: xml or properties


Singleton: from beginning to end, only one object is instantiated and created once, so that the members in the class will be initialized only once.
Multiple instances: the object is created many times, and the execution efficiency is not as high as that of a single instance object.


Three common implementation classes of ApplicationContext:
ClassPathXmlApplicationContext: it can load the configuration file under the classpath. It is required that the configuration file must be under the classpath. If it is not, it cannot be loaded (more commonly used)
FileSystemXmlApplicationContext: it can load configuration files under any path on the disk (must have access rights)
AnnotationConfigApplicationContext: it is used to read annotations and create containers

Problems caused by two interfaces of the core container:
ApplicationContext: singleton object is applicable to container objects. This interface is generally used to define container objects
When it creates the core container, the strategy of creating objects is to load immediately. That is, as soon as the configuration file is read, the objects configured in the configuration file will be created.
BeanFactory: applicable to multiple objects
When it creates the core container, the strategy of creating objects is to delay loading. In other words, when the object is obtained according to the id and when the object is really created.


There are three ways to create beans:
The first way: use the default constructor to create.
When the bean tag is used in the spring configuration file, followed by the id and class attributes, and there are no other attributes and tags.
The default constructor is used to create bean objects. At this time, if there is no default constructor in the class, the object cannot be created.

<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>

The second way: use the methods in the ordinary factory to create objects (use the methods in a class to create objects and store them in the spring container)

<bean id="instanceFactory" class="com.itheima.factory.InstanceFactory"></bean>
<bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>

The third way: use static methods in the factory to create objects (use static methods in a class to create objects and store them in the spring container)

<bean id="accountService" class="com.itheima.factory.StaticFactory" factory-method="getAccountService"></bean>

scope attribute of bean tag:
Scope: used to specify the scope of the bean
Value: single instance and multi instance are commonly used
Singleton: singleton (default)
prototype: multiple cases
Request: the scope of the request applied to the web application
session: the range of sessions used for web applications
Global session: the session scope (global session scope) that acts on the cluster environment. When it is not a cluster environment, it is a session

<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl" scope="prototype"></bean>

Lifecycle of bean object
Singleton object
Birth: the object is born when the container is created
Alive: the object is alive as long as the container is still there
Death: the container is destroyed and the object dies
Summary: the lifecycle of a singleton object is the same as that of a container
Multiple objects
Birth: the spring framework creates for us when we use objects
Alive: an object is alive as long as it is in use.
Death: when an object is not used for a long time and there is no other object reference, it is collected by the Java garbage collector

02Spring dependency injection

Dependency injection in spring
Dependency injection:
            Dependency Injection
Role of IOC:
Reduce coupling (dependencies) between programs
Dependency management:
Leave it to spring for maintenance in the future
The objects of other classes need to be used in the current class, which are provided by spring. We only need to explain in the configuration file
Dependency maintenance:
It is called dependency injection.
Dependency injection:
Data that can be injected: there are three types
Basic type and String
Other bean types (configured beans in the configuration file or annotated)
Complex type / collection type
There are three injection methods
The first is to use the constructor to provide
The second method: use the set method to provide
The third method: using annotation to provide

If the data changes frequently, it is not suitable for injection

Constructor injection:
Tag used: constructor ARG
Where the tag appears: inside the bean tag
Attributes in Tags
Type: used to specify the data type of the data to be injected, which is also the type of one or some parameters in the constructor
Index: it is used to specify the data to be injected and assign a value to the parameter specifying the index position in the constructor. The location of the index starts at 0
Name: used to assign a value to the parameter with the specified name in the constructor
=============The above three are used to assign values to which parameter in the constructor====================
value: used to provide data of basic type and String type
ref: used to specify other bean type data. It refers to bean objects that have appeared in spring's Ioc core container

Advantages:
When obtaining a bean object, injecting data is a necessary operation, otherwise the object cannot be created successfully.
Disadvantages:
The instantiation method of bean object is changed, so that if we can't use these data when creating an object, we must also provide them.

<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <constructor-arg name="name" value="Tess"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<!-- Configure a date object -->
<bean id="now" class="java.util.Date"></bean>

The set method is more commonly used
Tag involved: property
Where it appears: inside the bean tag
Label properties
Name: used to specify the name of the set method called during injection
value: used to provide data of basic type and String type
ref: used to specify other bean type data. It refers to bean objects that have appeared in spring's Ioc core container
Advantages:
There are no explicit restrictions when creating objects. You can directly use the default constructor
Disadvantages:
If a member must have a value, it is possible that the set method is not executed to get the object.

<bean id="accountService2" class="com.itheima.service.impl.AccountServiceImpl2">
        <property name="name" value="TEST" ></property>
        <property name="age" value="21"></property>
        <property name="birthday" ref="now"></property>
</bean>

Injection of complex type / injection of collection type
Label used to inject into the List structure collection:
            list array set
Labels for multiple Map structure collection injections:
            map  props
The structure is the same, and the labels can be interchanged

03Spring annotation IOC

Configuration of XML:

<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
       scope=""  init-method="" destroy-method="">
     <property name=""  value="" | ref=""></property>
</bean>

For creating objects
Their function is the same as that of writing a < bean > tag in the XML configuration file
       @Component:
Function: used to store the current class object into the spring container
Properties:
Value: used to specify the id of the bean. When we don't write it, its default value is the current class name, and the initial letter is changed to lowercase.
Controller: generally used in the presentation layer
Service: generally used in the business layer
Repository: generally used in the persistence layer
As like as two peas, Component and the above three annotations are exactly the same.
The three of them are the spring framework, which provides us with clear annotations for three-tier use, making our three-tier objects clearer

 
For injecting data
Their role is the same as writing a < property > tag in the bean tag in the xml configuration file
        Autowired:
Function: automatically inject by type. As long as there is a unique bean object type in the container that matches the variable type to be injected, the injection can succeed
If the type of any bean in the ioc container does not match the type of the variable to be injected, an error is reported.
If there are multiple types matching in the Ioc container:
Location:
It can be variable or method
Details:
When using annotation injection, the set method is not necessary.
       Qualifier:
Function: inject by name based on the injection in class. It cannot be used alone when injecting class members. However, when injecting method parameters, you can
Properties:
value: used to specify the id of the injected bean.
       Resource
Function: inject directly according to the id of the bean. It can be used independently
Properties:
name: used to specify the id of the bean.
The above three injections can only inject data of other bean types, while the basic type and String type cannot be implemented with the above annotation.
In addition, the injection of collection type can only be realized through XML.
 
       Value
Function: used to inject data of basic type and String type
Properties:
Value: used to specify the value of the data. It can use spiel in spring (that is, spring's el expression)
How to write spiel: ${expression}
 
Used to change the scope of action
Their function is the same as that of using the scope attribute in the bean tag
       Scope
Scope: used to specify the scope of the bean
Properties:
Value: the value of the specified range. Common value: singleton prototype
 
Life cycle related knowledge
Their role is the same as using init method and destroy method in bean tags
       PreDestroy
Function: used to specify the destruction method
       PostConstruct
Function: used to specify the initialization method

@Service("accountService")
//@Scope("prototype")
public class AccountServiceImpl implements IAccountService {

//    @Autowired
//    @Qualifier("accountDao1")
    @Resource(name = "accountDao2")
    private IAccountDao accountDao = null;

04Spring annotation configuration

core -> xmlns:context

New comments in spring:
Configuration
Function: Specifies that the current class is a configuration class
Details: when the configuration class is used as the parameter created by the AnnotationConfigApplicationContext object, the annotation may not be written.
  ComponentScan
Function: used to specify the package to be scanned by spring when creating containers through annotations
Properties:
value: it has the same function as base packages. It is used to specify the packages to be scanned when creating containers.
Using this annotation is equivalent to configuring in xml:

<context:component-scan base-package="com.itheima"></context:component-scan>

Bean
Function: used to store the return value of the current method into the ioc container of spring as a bean object
Properties:
Name: used to specify the id of the bean. When not written, the default value is the name of the current method
Details:
When we use annotation to configure a method, if the method has parameters, the spring framework will look for available bean objects in the container.
The search method is the same as that of Autowired annotation
   Import
Role of classes for import: other
Properties:
value: used to specify the bytecode of other configuration classes.
When we use the Import annotation, the class with the Import annotation is the parent configuration class, and the imported class is the child configuration class
   PropertySource
Function: used to specify the location of the properties file
Properties:
value: Specifies the name and path of the file.
Keyword: classpath, which indicates the class path

05Spring integrates JUnit configuration

Spring integrates junit configuration
1. Import the jar (coordinate) of spring integration junit
2. Use an annotation provided by Junit to replace the original main method with the one provided by spring
              @Runwith
3. Inform the spring runner whether spring and ioc are created based on xml or annotation, and specify the location
           @ContextConfiguration
locations: specify the location of the xml file and add the classpath keyword to indicate that it is under the classpath
classes: Specifies the location of the annotation class
 
When we use spring 5 In the X version, the jar of junit must be 4.12 or above
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)

@ContextConfiguration(locations = "classpath:bean.xml")

06Spring_ConnectionUtils

You need to use the ThreadLocal object to bind the Connection to the current thread,
Thus, there is only one object in a thread that can control transactions.

ConnectionUtils: the tool class of connection, which is used to obtain a connection from the data source and implement the binding with the thread

Transaction manager: a tool class related to transaction management, which includes,
Open transaction: connectionutils getThreadConnection(). setAutoCommit(false)
Commit transaction: commit()
Rollback transaction: rollback()
Release connection: close()

07 dynamic agent

Dynamic proxy:
Features: bytecode can be created with use and loaded with use
Function: enhance the method without modifying the source code
Classification:
Interface based dynamic agent
Subclass based dynamic agent
Interface based dynamic proxy:
Class involved: Proxy
Provider: JDK official
How to create a proxy object:
Use the newProxyInstance method in the Proxy class
Requirements for creating proxy objects:
The proxy class implements at least one interface. If not, it cannot be used
Parameters of newProxyInstance method:
ClassLoader: class loader
It is used to load the bytecode of the proxy object. Use the same class loader as the proxied object. Fixed writing.
Class []: bytecode array
It is used to make the proxy object and the proxied object have the same method. Fixed writing.
InvocationHandler: used to provide enhanced code
It is for us to write how to proxy. We generally refer to the implementation classes of this interface, which are usually anonymous internal classes, but they are not necessary.
Who writes the implementation classes of this interface.

IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(),
                producer.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * Function: any interface method that executes the proxy object will pass through this method
                     * Meaning of method parameters
                     * @param proxy   Reference to proxy object
                     * @param method  Currently executed method
                     * @param args    Parameters required by the current execution method
                     * @return        It has the same return value as the proxy object method
                     * @throws Throwable
                     */
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //Provide enhanced code
                        Object returnValue = null;

                        //1. Get the parameters of method execution
                        Float money = (Float)args[0];
                        //2. Judge whether the current method is sales
                        if("saleProduct".equals(method.getName())) {
                            returnValue = method.invoke(producer, money*0.8f);
                        }
                        return returnValue;
                    }
                });

Dynamic proxy:
Features: bytecode can be created with use and loaded with use
Function: enhance the method without modifying the source code
Classification:
Interface based dynamic agent
Subclass based dynamic agent
Subclass based dynamic proxy:
Class involved: Enhancer
Provider: third party cglib Library
How to create a proxy object:
Use the create method in the Enhancer class
Requirements for creating proxy objects:
The delegate class cannot be the final class
Parameters of create method:
Class: bytecode
It is the bytecode used to specify the proxy object.
         
Callback: used to provide enhanced code
It is for us to write how to proxy. We generally refer to the implementation classes of this interface, which are usually anonymous internal classes, but they are not necessary.
Who writes the implementation classes of this interface.
We usually write the sub interface implementation class of the interface: MethodInterceptor

Producer cglibProducer = (Producer)Enhancer.create(producer.getClass(), new MethodInterceptor() {
            /**
             * Any method that executes the proxied object passes through the method
             * @param proxy
             * @param method
             * @param args
             *    The above three parameters are the same as those of the invoke method in the interface based dynamic proxy
             * @param methodProxy : Proxy object of the current execution method
             * @return
             * @throws Throwable
             */
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                //Provide enhanced code
                Object returnValue = null;

                //1. Get the parameters of method execution
                Float money = (Float)args[0];
                //2. Judge whether the current method is sales
                if("saleProduct".equals(method.getName())) {
                    returnValue = method.invoke(producer, money*0.8f);
                }
                return returnValue;
            }
        });

08Spring_AOP

AOP: (Aspect Oriented Programming) Aspect Oriented Programming is a continuation of OOP (object oriented programming)
Function: during the running of the program, the existing methods are enhanced without modifying the source code
Advantages: reduce duplicate code, improve development efficiency and facilitate maintenance
Implementation: using dynamic agent technology

AOP related terms:
Joinpoint: refers to the intercepted points. In Spring, these points refer to methods,
Because Spring only supports connection points of method types (Methods in the business layer)
Pointout: refers to the definition of which joinpoints we want to intercept (enhanced methods)

Advice: notification refers to what to do after intercepting the Jointpoint
Notification type: pre notification, post notification, exception notification, final notification, surround notification.
Introduction: it is a special notice. Without modifying the class code,
Introduction can dynamically add some methods or fields for classes at run time
Target: the target object of the proxy
Weaving: refers to the process of applying enhancements to the target object to create a new proxy object
spring uses dynamic proxy weaving, while AspectJ uses compile time weaving and class loading time weaving.
Proxy: after a class is woven and enhanced by AOP, a result proxy class is generated.
Aspect: a combination of pointcut and notification (Introduction).

09Spring_AOP_XML configuration

XML based AOP configuration steps in spring
1. Leave the notification Bean to spring for management
2. Use the aop:config tag to indicate the start of AOP configuration
3. Use the aop:aspect tag to indicate the configuration section
id attribute: it provides a unique identification for the section
ref attribute: is the Id of the specified notification class bean.
4. Use the corresponding tag inside the aop:aspect tag to configure the notification type
Our current example is to make the printLog method before the pointcut method is executed: so it is a pre notification
aop:before: indicates to configure pre notification
Method attribute: used to specify which method in the Logger class is pre notification
Pointcut attribute: used to specify the pointcut expression. The meaning of the expression refers to which methods in the business layer are enhanced

How to write the pointcut expression:
Keyword: execution (expression)
Expression:
Access modifier , return value , package name Package name Package name Class name Method name (parameter list)
Standard expression:
                    public void com.itheima.service.impl.AccountServiceImpl.saveAccount()
The access modifier can be omitted
                    void com.itheima.service.impl.AccountServiceImpl.saveAccount()
The return value can use wildcards to represent any return value
                    * com.itheima.service.impl.AccountServiceImpl.saveAccount()
The package name can use wildcards to represent any package. However, if there are several levels of packages, you need to write several *
                    * *.*.*.*.AccountServiceImpl.saveAccount())
Package name can use Represents the current package and its sub packages
                    * *..AccountServiceImpl.saveAccount()
Both class and method names can be configured by using *
                    * *..*.*()
Parameter list:
Data types can be written directly:
Basic type direct write name: int
Reference type write package name The method of class name is Java lang.String
You can use wildcards to represent any type, but you must have parameters
Can use It indicates whether there are parameters or not. Parameters can be of any type
All pass configuration:
                    * *..*.*(..)

The common writing method of pointcut expression in actual development:
Switch to all methods under the business layer implementation class
                        * com.itheima.service.impl.*.*(..)

    <!-- to configure Logger class -->
    <bean id="logger" class="com.itheima.utils.Logger"></bean>

   

<!--to configure AOP-->
    <aop:config>
        <!-- Configure pointcut expressions id Property specifies the unique identity of the expression. expression Property is used to specify the content of the expression
              This label is written in aop:aspect The inside of the label can only be used in the current section.
              It can also be written in aop:aspect Outside, all sections are available at this time
          -->
        <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
        <!--Configuration section -->
        <aop:aspect id="logAdvice" ref="logger">
            <!-- Configure pre notification: executed before the pointcut method is executed
            <aop:before method="beforePrintLog" pointcut-ref="pt1" ></aop:before>-->

            <!-- Configure post notification: the value after the pointcut method is executed normally. It and exception notification can always be executed only once
            <aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>-->

            <!-- Configure exception notification: executed after the exception is generated during the execution of pointcut method. It and post notification can always be executed only once
            <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>-->

            <!-- Configure final notification: the pointcut method executes after it whether it executes normally or not
            <aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>-->

            <!-- Configure surround notifications-->
            <aop:around method="aroundPringLog" pointcut-ref="pt1"></aop:around>
        </aop:aspect>
    </aop:config>

pom.xml:   

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>
</dependencies>

Around Advice
Question:
When we configure the surround notification, the pointcut method is not executed, but the notification method is executed.
Analysis:
By comparing the surround notification code in the dynamic agent, it is found that the surround notification of the dynamic agent has a clear entry point method call, but not in our code.
Solution:
The Spring framework provides us with an interface: proceeding joinpoint. The interface has a method, procedure (), which is equivalent to explicitly calling the pointcut method.
This interface can be used as a method parameter surrounding the notification. During program execution, the spring framework will provide us with the implementation class of this interface for us to use.
     
Surround notifications in spring:
It is a way for us to manually control when the enhancement method is executed in the code provided by the spring framework.

public Object aroundPringLog(ProceedingJoinPoint pjp){
        Object rtValue = null;
        try{
            Object[] args = pjp.getArgs();//Get the parameters required for method execution

            System.out.println("Logger Class aroundPringLog Method starts logging... Front");

            rtValue = pjp.proceed(args);//Explicitly call business layer methods (pointcut methods)

            System.out.println("Logger Class aroundPringLog Method starts logging... Postposition");

            return rtValue;
        }catch (Throwable t){
            System.out.println("Logger Class aroundPringLog Method starts logging... abnormal");
            throw new RuntimeException(t);
        }finally {
            System.out.println("Logger Class aroundPringLog Method starts logging... final");
        }
}

10Spring_AOP_ Annotation configuration

@Component("logger")
@Aspect//Indicates that the current class is a faceted class
public class Logger {

    @Pointcut("execution(* com.itheima.service.impl.*.*(..))")
    private void pt1(){}

    /**
     * Before advice 
     */
//    @Before("pt1()")
    public  void beforePrintLog(){
        System.out.println("Before advice  Logger Class beforePrintLog Method starts logging...");
    }

    /**
     * Post notification
     */
//    @AfterReturning("pt1()")
    public  void afterReturningPrintLog(){
        System.out.println("Post notification Logger Class afterReturningPrintLog Method starts logging...");
    }
    /**
     * Exception notification
     */
//    @AfterThrowing("pt1()")
    public  void afterThrowingPrintLog(){
        System.out.println("Exception notification Logger Class afterThrowingPrintLog Method starts logging...");
    }

    /**
     * Final notice
     */
//    @After("pt1()")
    public  void afterPrintLog(){
        System.out.println("Final notice Logger Class afterPrintLog Method starts logging...");
    }

@Around("pt1()")
    public Object aroundPringLog(ProceedingJoinPoint pjp){
        Object rtValue = null;
        try{
            Object[] args = pjp.getArgs();//Get the parameters required for method execution

            System.out.println("Logger Class aroundPringLog Method starts logging... Front");

            rtValue = pjp.proceed(args);//Explicitly call business layer methods (pointcut methods)

            System.out.println("Logger Class aroundPringLog Method starts logging... Postposition");

            return rtValue;
        }catch (Throwable t){
            System.out.println("Logger Class aroundPringLog Method starts logging... abnormal");
            throw new RuntimeException(t);
        }finally {
            System.out.println("Logger Class aroundPringLog Method starts logging... final");
        }
    }
}

pom.xml:

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- to configure spring Packages to scan when creating containers-->
    <context:component-scan base-package="com.itheima"></context:component-scan>

    <!-- to configure spring Open annotation AOP Support of -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

Configuration without XML:

@Configuration
@ComponentScan(basePackages="com.itheima")
@EnableAspectJAutoProxy
public class SpringConfiguration{
}

11Spring_JdbcTemplate

JdbcTemplate in spring
Function of JdbcTemplate:
It is used to interact with the database and realize CRUD operation on tables
How to create this object:
Object: POM xml:

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
</dependencies>

Define the encapsulation policy of Account

class AccountRowMapper implements RowMapper<Account>{
    /**
     * Encapsulate the data in the result set into accounts, and then spring adds each Account to the collection
     * @param rs
     * @param rowNum
     * @return
     * @throws SQLException
     */
    @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;
    }
}

12introduction to spring transaction control API

PlatformTransactionManager:
3 specific operations:
Get transaction status information: transactionstatus gettransaction (transactiondefinition)
Commit transaction: void commit (transactionstatus status)
Rollback transaction: void rollback (transactionstatus)
Implementation class: DataSourceTransactionManager (used when spring JDBC or IBatis persistes data)
Hibernate transaction manager (used when using hibernate version to persist data)

TransactionDefinition:
Get transaction object name: String getName()
Get transaction isolation level: int getIsolationLevel()
Get transaction propagation behavior: int getPropagationBehavior() (addition, deletion and modification)
Get transaction timeout: int getTimeout()
Get whether the transaction is read-only: boolean isReadOnly() (query)

13Spring_XML transaction control

Data Access -> xmlns:txpom.xml:

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
</dependencies>

bean.xml:

<!-- spring Medium based XML Declarative transaction control configuration steps for
        1,Configure transaction manager
        2,Configure notifications for transactions
                At this point, we need to import transaction constraints tx Namespaces and constraints are also required aop of
                use tx:advice Tag configuration transaction notification
                    Properties:
                        id: A unique identifier for transaction notification
                        transaction-manager: Provide a transaction manager reference to the transaction notification
        3,to configure AOP Generic pointcut expressions in
        4,Establish the corresponding relationship between transaction notification and pointcut expression
        5,Configure the properties of the transaction
               Is the notification of the transaction tx:advice Inside of label

     -->
    <!-- Configure transaction manager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- Configure notifications for transactions-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- Configure the properties of the transaction
                isolation: Specifies the isolation level of the transaction. The default value is DEFAULT,Indicates that the default isolation level of the database is used.
                propagation: Specifies the propagation behavior of the transaction. The default value is REQUIRED,It means that there will be transactions. You can choose to add, delete or modify. The query method can be selected SUPPORTS. 
                read-only: Used to specify whether a transaction is read-only. Only query methods can be set to true. The default value is false,Indicates reading and writing.
                timeout: Used to specify the timeout of a transaction. The default value is-1,Means never timeout. If a value is specified, it is in seconds.
                rollback-for: Used to specify an exception. When this exception occurs, the transaction will be rolled back. When other exceptions occur, the transaction will not be rolled back. There is no default value. Indicates that any exceptions are rolled back.
                no-rollback-for: It is used to roll back an exception when the transaction generates no other exception. There is no default value. Indicates that any exceptions are rolled back.
        -->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>

    <!-- to configure aop-->
    <aop:config>
        <!-- Configure pointcut expressions-->
        <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
        <!--Establish the corresponding relationship between pointcut expression and transaction notification -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>

14Spring_ Annotation transaction control

bean.xml:

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- to configure spring Packages to scan when creating containers-->
    <context:component-scan base-package="com.itheima"></context:component-scan>

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

    <!-- Configure data source-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
        <property name="username" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>

    <!-- spring Annotation based declarative transaction control configuration steps in
        1,Configure transaction manager
        2,open spring Support for annotation transactions
        3,Use where transaction support is needed@Transactional annotation


     -->
    <!-- Configure transaction manager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- open spring Support for annotation transactions-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

</beans>

@Transactional(propagation= Propagation.SUPPORTS,readOnly=true) / / configuration of read-only transactions
@Transactional(propagation= Propagation.REQUIRED,readOnly=false) / / read / write transaction configuration
 

15Spring_ Full annotation transaction control

SpringConfiguration.class:

/**
 * spring Configuration class, equivalent to bean xml
 */
@Configuration
@ComponentScan("com.itheima")
@Import({JdbcConfig.class,TransactionConfig.class})
@PropertySource("jdbcConfig.properties")
@EnableTransactionManagement
public class SpringConfiguration {
}


JdbcConfig.class:

/**
 * Configuration classes related to connecting to the database
 */
public class JdbcConfig {

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    /**
     * Create a JdbcTemplate
     * @param dataSource
     * @return
     */
    @Bean(name="jdbcTemplate")
    public JdbcTemplate createJdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }

    /**
     * Create data source object
     * @return
     */
    @Bean(name="dataSource")
    public DataSource createDataSource(){
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
}


TransactionConfig.class:
/**
 * Transaction related configuration classes
 */
public class TransactionConfig {

    /**
     * Used to create a transaction manager object
     * @param dataSource
     * @return
     */
    @Bean(name="transactionManager")
    public PlatformTransactionManager createTransactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}


 

Keywords: Java Spring SSM

Added by Allenport on Tue, 08 Feb 2022 16:30:09 +0200