General review of Spring framework

Spring framework

1: Frame

idea:

Making the existing technology easier to use is itself a hodgepodge, integrating the existing technology framework

:SSM :

SpringMVC +Spring +MyBatis

1.spring configuration file

1.1: jar package dependency

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>spring06</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>spring06 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.3.5</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.5</version>
    </dependency>
<!--JUnit Is an open source Java Test framework for writing and running repeatable tests-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

</project>

1.2:spring.xml configuration file header tag

<?xml version="1.0" encoding="UTF-8"?>
        <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
                xmlns:util="http://www.springframework.org/schema/util"
                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-3.2.xsd
                      http://www.springframework.org/schema/context
                      http://www.springframework.org/schema/context/spring-context-3.2.xsd
                      http://www.springframework.org/schema/util
                      http://www.springframework.org/schema/util/spring-util-3.2.xsd">

                 <!-- Open attribute annotation -->
                  <context:annotation-config />
            
            <!--Enable annotation support     in use AOP in-->
            <aop:aspecttj-autoproxy/>
                 

1.3: Notes

-@Autowired :Auto assembly pass type, name if Autowired  If the attribute cannot be uniquely automatically assembled, you need to pass the-@Qualifier(value="xxx")
-@Nullable The field is marked with this annotation, indicating that this field can be null
-@Resource:Automatic assembly by name, type

-@Component :The component is placed on the class, indicating that the class is Spring Managed



1.4: expansion

Write entity and string look

1.4.1: in POM Add in XML
 <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.18</version><!--  -->
    </dependency>
1.4.2. Add in entity class
Add comments on the entity class during specific usage

@Data//Automatically generate get, set and toString
@NoArgsConstructor//Auto generate parameterless constructor
@AllArgsConstructor//Automatically generate full parameter constructor

@Setter: Annotation on attributes; Provide for properties setting method

@Getter: Annotation on attributes; Provide for properties getting method
@Log4j : Annotation on class; Provide the class with a property named log of log4j Log object
1.4.3 example:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data   //Automatically generate get, set and tostring
@NoArgsConstructor  //Automatic generation of parameterless structure
@AllArgsConstructor  //Automatically generate full parameter constructor
public class Person {
    public String name;
    public Dog dog;
    public  Cat cat;

}

1.4.4:Spring Book

A rapidly developed scaffold

Based on SpringBoot, you can quickly develop a single microservice

Contract greater than configuration

Spring Cloud is implemented based on Spring Boot

1.5: advantages

1.:Spring is an open source free framework (container)

2.Spring is a lightweight, non intrusive framework

3. Control inversion (IOC), aspect oriented programming (AOP)

4. Support transaction processing and framework integration

1.6: summary

Spring is a lightweight inversion of control (IOC) and aspect oriented programming (AOP) framework!

1.7: composition

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-kgmvi9cn-1619590998926) (capture (3)] - 1619324153526 PNG)

2: IOC theoretical derivation

1.dao interface

2.daoimpl implementation class

3.service interface

4. Serviceimpl business implementation class

2.1: set for dynamic implementation value injection

//userDao interface
public void  setUserDao(UserDao  userDao){
    this.userDao=userDao;
}


//Implementation class
((UserServiceImpl)  userServise).setUserDao(new UserDaoSqlServerImpl);

userService.getUser();

In our previous business, the needs of users may affect our original code. We need to modify the source code according to the needs of users

We use a Set interface to realize the benefits

1. Previously, the program actively created objects, and the control was in the hands of the program

2. Use set to inject control in the hands of the user

This idea essentially solves the problem. We don't have to manage the creation of objects. The system coupling is greatly reduced, and you can focus more on business implementation. This is the original of IOC! (2) PNG)

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-9bzvegqe-1619590998928) (capture 1-1619312357645.PNG)]

IOC essence

Control inversion is a design idea. DI (dependency injection) is a method to realize IOC. In programs without IOC, we use object-oriented programming. The creation of objects and the dependencies between objects are completely hard coded in the program. The creation of objects is controlled by the program itself. Control inversion is the creation of objects to others

Personally, I think inversion means that the way to obtain dependent objects is reversed

IOC is the core content of Spring. We use a variety of methods to perfectly implement IOC,

Inversion of control is a way to produce or obtain specific objects through description (xml or annotation) and through a third party. In Spring, IOC container is used to implement control inversion, and its implementation method is Dependency injection (DI)

1. Import jar package
Two jar package
 
 spring-webmvc
 spring-jdbc
 
2. Create an entity class
public class hello

3. Write spring XML file

<!--use Spring To create objects,stay spring These are called BEan

Type variable name=new Type ();

bean =object   new hello();

id=Variable name
class = new Object of

property It is equivalent to setting a value for the attribute in the queue image

-->
<bean id="hello " class="com.zhke.pojo.hello">
    <property name="str"  value="Spring"/>
    
    <!--
ref:quote Spring Created object in container
value: Specific value, basic data type


-->
 
    
    
    
</bean>

Test class
//Get spring context object
//Get ApplicationContext spring container
ApplicationContext   context=new ClassPathxmlApplictionContext("beans.xml")
//Our objects are now managed in Spring. If we use them, we can get them directly
    
   hello hello= context.getBean("hello")
    
   

This process is control reversal

Control:

Who controls the creation of objects? After using spring, objects are created by spring

reversal:

The program itself does not create an object, but becomes a passive acceptance object

Dependency injection:

Is to use the set method for injection

IOC is a programming idea, from active programming to passive acceptance

To implement different operations, you only need to modify them in the xml file.

IOC is: objects are created, managed and assembled by Spring

How IOC creates objects

1. Create an object through nonparametric construction. The default is

2. Suppose we create objects with parametric constructs

1. Subscript assignment
<constructor -arg index="0" value ="Node"/>
2. Type creation
<!-- Create by type-->
     <constructor-arg type="java.lang.String" value="idiot"/>
3. By parameter type
<!--By parameter type-->
        <constructor-arg name="name" value="hg " />
Summary:

When the configuration file is loaded, the objects managed in the container have been initialized

Spring configuration

Alias:
<!--Alias, which is set directly by parameter name-->

<alias name="user" alias="userNew"
Bean configuration
<!--
id:bean The unique identifier of, that is, the object name we learned
class : bean Fully qualified name corresponding to object: package
 name + type
name : It is also an alias, and multiple aliases are taken at the same time
-->

<bean id="user" class="com.zhke.pojo.user" name="user1">

<property name="name" value="west"/>

</bean>
import

This import is generally used for team development. It can import and merge multiple configuration files into one

Dependency injection (DI)

1. Constructor injection

2. Inject [key points] through set

Dependency injection: set injection

Dependency: the creation of bean objects depends on the container

Injection: all properties in the bean object,

Environment construction:

1. Complex type

package com.zhke.pojo;

public class address {
    private address address;

    public com.zhke.pojo.address getAddress() {
        return address;
    }

    public void setAddress(com.zhke.pojo.address address) {
        this.address = address;
    }
}
2. Real test object
public class Student {
    private String name;
    private address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String > games;
    private String wife;
    private Properties info;
3.spring.xml
<!--Common injection basic data type   value-->
<bean id="student" class="com.zhke.pojo.Student">

        <property name="name" value="Zhang Shan"/>

    </bean>
4. Testing
 ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

        Student student = (Student) context.getBean("student");
        System.out.println(student.getName());

    }
5. Various injections
##### <?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-3.0.xsd">


    <bean id="add" class="com.zhke.pojo.address">
        <property name="address" value="better"/>
<!--        <property name="address" value="bank"/>-->
    </bean>

    <!--Common injection basic type value-->
    <bean id="student" class="com.zhke.pojo.Student">

        <property name="name" value="Zhang Shan"/>

         <!--Reference injection reference type  ref-->

         <property name="address" ref="add"/>

<!--Array type set injection-->
<!--    <bean id="books" class="com.zhke.pojo.Student">-->
        <property name="books">
            <array >
                <value> The Dream of Red Mansion</value>
                <value> Journey to the West</value>
                <value> Water Margin</value>
                <value> Romance of the Three Kingdoms</value>
            </array>
        </property>
<!--    </bean>-->

<!--  list-->
<!-- <bean id="hobbys" class="com.zhke.pojo.Student">-->
     <property name="hobbys" >
         <list>
             <value>Play games</value>
             <value>Read novels</value>
             <value>Beat beans</value>
         </list>

     </property>

<!--map injection-->
<property name="card" >
    <map>
        <entry key="ID" value="411326"/>
        <entry key="Student number" value="20183230"/>
        <entry key="cell-phone number" value="123105"/>
    </map>
</property>
<!--    set injection-->
<property name="games">
    <set>
        <value>Spicy strip</value>
        <value>Weilong spicy strip</value>
        <value>Mogan pepper</value>

    </set>
</property>

<!--     null injection   -->

        <property name="wife">
            <null/>
        </property>
<!-- Properties injection-->
<property name="info">
    <props>
<prop key="QQ number">123</prop>
        <prop key="pork">40</prop>
    </props>
</property>

    </bean>
</beans>


Expansion mode injection

<!--Important: the header file has two links-->
<beans 
       xmles:p="http://www.springframework.org/schema/p"
 xmles:c="http://www.springframework.org/schema/c"
       


<!--p Namespace injection, you can directly inject the value of the attribute: property-->
<bean id="user" class="com.kuang.pojo.User" p:name="Lyophilized powder"  page="18"/>
<!--c Namespace injection through constructor: construct-args-->
<bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="pepper"/>

</beans>

Note: it cannot be used directly. You need to import xml constraints

bean Scopes

Singleton mode (spring default mechanism)

  <bean name="user1" class="com.zhke.pojo.User " c:age="415" c:name="environment" scope="singleton"/>

Prototype mode: every time you get from the container, an experience object will be generated

    <bean name="user1" class="com.zhke.pojo.User " c:age="415" c:name="environment" scope="prototype"/>

7:Bean auto assembly

Automatic assembly is a way for Spring to meet bean dependencies

Spring will automatically find in the context and automatically assemble properties for the bean

There are three ways in spring

1. Configuration displayed in xml

2. Configure in java

3. Implicit automatic assembly (key)

autowire (automatic assembly)

byname: it will automatically find the beanid corresponding to the value after the set method of its own object in the container context

 <bean id="person" class="com.zhke.pojo.Person" autowire="byName">
               <property name="name" value="station"/>

bytype: it will automatically find the bean with the same attribute type as its own object in the container context

  <bean  class="com.zhke.pojo.Dog"/>
    <bean  class="com.zhke.pojo.Cat"/>
           <bean id="person" class="com.zhke.pojo.Person" autowire="byType">
               <property name="name" value="station"/>


           </bean>

Summary:

When byname: is used, the ID of the bean needs to be unique, and the bean needs to be consistent with the set method of the automatically injected attribute

When bytype, you need to ensure that the class of all beans is unique, and the bean needs to be consistent with the type of automatic injection

Automatic assembly using annotation development

Annotations supported by jdk 1.5

Spring2.5 supporting notes

To use the annotation header file

<?xml version="1.0" encoding="UTF-8"?>
        <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
                xmlns:util="http://www.springframework.org/schema/util"
                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-3.2.xsd
                      http://www.springframework.org/schema/context
                      http://www.springframework.org/schema/context/spring-context-3.2.xsd
                      http://www.springframework.org/schema/util
                      http://www.springframework.org/schema/util/spring-util-3.2.xsd">

                 <!-- Open attribute annotation -->
                  <context:annotation-config />
</beans>

1. Import context constraint

2. Supporting context for configuring annotations: annotation config

@Autwired

Automatic injection can be used directly on attributes or set methods

Using Autwired, we don't need to write the set method, the premise is

The properties of the auto assembly are in IOC (spring container), and match the name byname

polular science:

@Nullable   The field is marked with this annotation, indicating that this field can be null
    

If the @ AUtwired automatic assembly environment is complex and the automatic assembly cannot be completed through annotation, it can be used together

@Qualifier (value = "xxxx") can be used with @ Autwired

@Resource

@Difference between Resource and @ Autowired

They are used for automatic assembly and can be placed in the attribute field

difference

@Autowired is implemented by bytype, and this object must exist

@Resource is implemented by byname. If the name cannot be found, it is implemented by bytype. If it cannot be found, an error will be reported

Execution order is different

Using annotation development

The use of annotations requires that the guide package be preceded by

Scanner
<context :compoent-scan base-pacjage : "com.zhke"/>

How to inject attributes

@Component
 Equivalent to <bean id ="user" class="com.zhke.pojo.User"/>
@Component   assembly 

@Value("environment")
    amount to 
    <property name="name" value="environment"/>

Derived annotation

@There are several derived annotations for the contribution. In web development, we will layer according to the MVC three-tier architecture

dao [@Repositoty]

sevice [@Service]

controller [Controller]

The functions of these four annotations are the same. They all represent the assembly Bean of a class registered in Spring

Scope

Scope ("prototype") single example

Summary

xml and annotation

xml is more versatile, suitable for any occasion, and easy to maintain

The class that cannot be maintained is relatively complex, not its own

xml and annotation best practices:

xml is used to manage bean s;

Annotation is only responsible for completing attribute injection;

We only need to pay attention to one problem in the process of using, and we must make the annotation effective

<!--Specify the package to be scanned, and the annotation under this package will take effect-->
<context:component-scan base-psckage="com.zhke"/>
<!--Open attribute annotation-->
<context:annotation-config/>

3: Agent mode

Why learn agent mode

Because this is the bottom layer of spring AOP [spring AOP and spring MVC] required test

3.1: Agent Mode

[the external chain picture transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-63NroHLj-1619590998930)(G: \ learning first \ spring \ picture \ 4.PNG)]

3.1.1: static agent:

Role analysis

Abstract role: it is usually solved by using interfaces or abstract classes

Real role: the role represented

Role of agent: This is the role of agent. After representing the real role, we usually do some ancillary operations

Customer: the person who visits the object

Code steps

1. Interface

public interface Rent {
    public void rent();
}

2. Real role

public class House  implements Rent, jia{
    @Override
    public void rent() {
        System.out.println("Landlord renting house");
    }


    @Override
    public void furniture() {
        System.out.println("The landlord sells furniture");
    }
}

3. Agent role

public class Agent {
    private House house;


    public Agent() {
    }

    public Agent(House house) {
        this.house = house;
    }

     public void rent(){
         house.rent();
          money();
          seeHouse();
          house.furniture();
     }


     public void money(){
         System.out.println("Intermediary said money");
     }
     public void seeHouse(){
         System.out.println("Intermediary showings");
     }


}

4 client role

public class Person {
    private static House rent;

    public static void main(String[] args) {
        //The landlord wants to rent the house
        House house = new House();
//        house.rent();
        //Agent rental
        Agent agent = new Agent(house);

        //You don't have to rent from the landlord and go straight to an intermediary
        agent.rent();
    }
}

3.1.2: benefits of agent mode:

It can make the operation of real characters more pure, without paying attention to some public businesses

The public is handed over to the agent role to realize the division of business

When the public business is expanded, it is convenient for centralized management

Disadvantages:

A real role will produce a proxy role: the amount of code will double and the development efficiency will be low

AOP in-depth understanding

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ZwflBike-1619590998933)(aop.PNG)]

3.2: dynamic agent (using reflection)

Dynamic agents have the same role as static agents

The agent class of dynamic agent is generated dynamically, which is not written directly

Dynamic agents fall into two categories

: interface based dynamic proxy, class based dynamic proxy

Interface based - jdk dynamic proxy [we use this]

Class based: cglib

java bytecode: javaAssist

English word: reflect

You need to know two classes: proxy

It provides static methods for creating dynamic agents and cities, and it is also created by these methods

inocattionHandler ()

Universal agent class code (only need to modify house)

public  class ProxyInvocationHAndler implements InvocationHandler {

//Proxy interface

       private  Object house;

    public void setHouse(Object house) {
        this.house = house;
    }

    //Generate proxy class
    public Object getProxy() {

      return   Proxy.newProxyInstance(this.getClass().getClassLoader(), house.getClass().getInterfaces(),this);

    }

//Process dailishil and return the result

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = method.invoke(house, args);
        return null;
    }
}
r

Test class

       House house = new House();

        //delegable role
        ProxyInvocationHAndler pih = new ProxyInvocationHAndler();

        //Handle the interface object we want to call by calling the program processing role
        //Sets the object to proxy
        pih.setHouse(house);
       //Proxy is generated by dynamic proxy
         Rent proxy = (Rent) pih.getProxy();
         proxy.rent();
    }
}


Benefits of dynamic agents

1. It can make the operation of real roles more pure without paying attention to some public businesses

2. Public is to hand over the role of agent, which realizes the division of business

3. When the public business is expanded, it is convenient for centralized management

4. A dynamic agent class represents an interface, which is generally the corresponding type of business

5. A dynamic proxy class can proxy multiple classes as long as it implements the same interface

4: AOP

4.1: what is AOP

AOP means: aspect oriented programming, which realizes the same maintenance of program functions through precompiled mode and runtime dynamic agent. AOP is the continuation of OOP, a hot spot in software development and an important content of Spring framework. It is a derivative generic of functional programming. Using AOP, each part of business logic can be divided, so as to reduce the coupling degree of each part of business logic, improve the importance of program and improve the efficiency of development.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-uxteini-1619590998935) (aop1. PNG)]

4.2: the role of AOP in spring

Provides transactions that allow users to customize aspects

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-oQ1MZeIs-1619590998936)(aop03.PNG)]

4.3: in Spring AOP, the horizontal cutting logic is defined through Advice, and Spring supports Advice of type 5

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Ld7dXgOx-1619590998937)(aop04.PNG)]

That is to increase the function of the heart without changing the original code

4.4: using Spring to implement AOP

[key] to use AOP weaving, you need to import a dependency package

aspectjweaver
4.4.1: Method 1: use Spring Api interface MethodBeforAdvice APi interface [mainly implemented by Spring Api interface]
public class log implements MethodBeforeAdvice {
    //Method: the method of the object to execute
    //args: parameter
    //Target: target object

    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"of"+method.getName()+"Executed");
    }
}

2.spring. Configuration in XML

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

<!--    &lt;!&ndash; Open attribute annotation &ndash;&gt;-->
<!--    <context:annotation-config />-->
    <bean id="userService" class="com.zhke.service.UserServiceImpl"/>
    <bean id="log" class="com.zhke.log4j.log"/>

<!--Method 1: use native Spring Api Interface-->
<!--    to configure aop-->
<aop:config>
<!--    breakthrough point  expression   expression: execution(Location to execute  *****)-->
    <aop:pointcut id="pointcut" expression="execution(* com.zhke.service.UserServiceImpl.*(..))"/>
<!--Execute surround increase-->
    <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
 </aop:config>


</beans>

In spring aop constraint in import XML

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

4.4.2: Method 2: implement AOP by customization [mainly section definition]
public void before(){
    System.out.println("Before method execution")
}
<!--Custom class-->
<bean id=diy class="com.zhke.diy"/>
<aop:config>
<!--Custom section,-->
    <aop:aspect ref="diy">
    <!--breakthrough point-->
        <aop:pointcut id="point" expression="execution" ( * com.zhke.service.UserServiceImpl.*(..))/>
        <!--notice-->
        <aop:before method="before" pointcut-ref="point"/>
    </aop:aspect>
</aop:config>
        
</aop:config>
4.4.3: implement with annotation
//Implement AOP with annotation
@Aspect  //Mark that this class is a facet
public class An(){
    @Before("execution (* com.zhke.service.UserServiceIpml.*(..))")
    System.out.print("Before method execution")
public void befre(){
    
  
    System.out.print("Before method execution")
}
    
     // @After('') after method execution
    @After("execution(* com.zhke.service.UserServiceImpl.*(..))")
   public void after(){
       System.out.println("After method execution");
   }
  
   
   //@Around ("") in surround enhancement, we can give a parameter to represent the entry point we want to get processing
    
 @Around("execution(* com.zhke.service.UserServiceImpl .*(..))")
    
    public void around(ProceedingJoinPOint jp) throws Throwable{
    
     Object proceed=jp.proceed();//Execution method   
    
    
    }
    
    
   //joinPoint gets the pointcut
    
    
}
<!--Enable annotation support-->
<aop:aspecttj-autoproxy/>

5: Integrate myBatis

Go find jar on maven

Steps:

1. Import jar package

junit

mybatis

mysql database

spring related

aop weaving [aspectjweaver]

mybatis-spring [new ]

longbook

2. Prepare configuration file

3. Test

Recall mybatis

1. Write entity class

2. Preparation of the core document

3. Write interface

4. Prepare mapping xml

5. Test

1. Basic steps of mybatis

1. Import jar package

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.6</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.46</version>
    </dependenc>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>



  </dependencies>


  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
    </resources>
  </build>


1. Write entity class

public class User {
    private int uid;
    private String uusername;
    private String upassword;

2. Write interface

public interface UserMapper {
    public List<User> SelectAll();
}

3. Write mapper xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhke.mapper.UserMapper">

    <select id="SelectAll" resultType="com.zhke.pojo.User">
    select * from user

    </select>
</mapper>

3. Write mybatis xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>



    <!-- and spring After integration environments Configuration will be abolished -->
    <environments default="development">
        <environment id="development">
            <!-- use jdbc transaction management -->
            <transactionManager type="JDBC" />
            <!-- Database connection pool -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mydb?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="com.zhke.mapper"/>
    </mappers>

</configuration>


4.log4j .xml

log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO

5. Write MyBatisUitl to turn it into singleton mode

  private void MyBatisUitl(){}
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }

}

6. Test

public class mytest {
    public static void main(String[] args) {

        SqlSessionFactory factory = MyBatisUtil.getSqlSessionFactory();
        SqlSession session = factory.openSession(true);
//        List<User> users = session.selectList();


        UserMapper mapper = session.getMapper(UserMapper.class);
       List<User> users = mapper.SelectAll();
        for (User user : users) {
            System.out.println(user);
        }
    }
}

2.mybatis spring integration

What is mybatis spring

He will help you talk about the seamless integration of mybatis into spring

Xxtemplate: template

1: step

1. Write data source

<?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">

2.sqlSessionFactory

<!--    to configure SQL sessionFactory  relation MyBatis-->

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
<!--        relation mybatis -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/zhke/mapper/*.xml"/>
    </bean>

3.sqlSessionTemplate

<!--    register sqlSessionTemplate relation sqlSessionFactory-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">

<!--Using constructor injection-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

4. It is necessary to add an implementation class [] to the interface

public class UserMapperImpl implements UserMapper{
    //sqlSession does not need to be created by ourselves, but managed by spring
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public List<User> SelectAll() {

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);


        return mapper.SelectAll();
    }
}

5. Inject the entity class written by yourself into speed In XML

 ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
            UserMapper userDao = (UserMapper) context.getBean("userDao");
            List<User> users = userDao.SelectAll();
            for (User user : users) {
                System.out.println(user);

6: Declarative transaction

1. Retrospective services

1. Treat a group of businesses as a business: either succeed or fail

2. Transaction is very important in project development, which involves data consistency and cannot be careless

3. Ensure integrity and consistency

Transaction ACID principle

Atomicity

uniformity

Isolation

Multiple businesses may operate the same resource to prevent data corruption

Persistence

Once the transaction is committed, no matter what happens to the system, the result will not be affected and will be written to the memory persistently "

2. Transaction management in spring

Declarative transaction: AOP
Programming affairs: [basically not used]

<!--Configure declarative transactions-->
<bean id="teansactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource " ref="dataSource"/>
    
    <!--combination AOP Implement transaction injection-->
   <!--Configure transaction notifications-->
    <tx:advice id="txAdvice" transaction-manager="transactionMAnager">
 <!--Which methods are configured with transactions-->   
  <!--Configure the propagation characteristics of transactions: new  propagation-->
        <tx:attributes>
        
        <tx:method name="*"/>
        
        </tx:attributes>
    
    
 </tx:advice>


</bean>



<!--Configure transaction entry-->
<aop:config>
<aop:pointcut id="txPointCut" expression="exection(* com.zhke.mapper.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>

</aop:config>

3. Why services are needed

If transactions are not configured, there may be inconsistent data submission

If we do not configure declarative transactions in SPRING, we need to manually configure transactions in the code

= sqlSession;
}

@Override
public List<User> SelectAll() {

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);


    return mapper.SelectAll();
}

}



5.Inject the entity class written by yourself into speing.xml in

```java
 ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
            UserMapper userDao = (UserMapper) context.getBean("userDao");
            List<User> users = userDao.SelectAll();
            for (User user : users) {
                System.out.println(user);

6: Declarative transaction

1. Retrospective services

1. Treat a group of businesses as a business: either succeed or fail

2. Transaction is very important in project development, which involves data consistency and cannot be careless

3. Ensure integrity and consistency

Transaction ACID principle

Atomicity

uniformity

Isolation

Multiple businesses may operate the same resource to prevent data corruption

Persistence

Once the transaction is committed, no matter what happens to the system, the result will not be affected and will be written to the memory persistently "

2. Transaction management in spring

Declarative transaction: AOP
Programming affairs: [basically not used]

<!--Configure declarative transactions-->
<bean id="teansactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource " ref="dataSource"/>
    
    <!--combination AOP Implement transaction injection-->
   <!--Configure transaction notifications-->
    <tx:advice id="txAdvice" transaction-manager="transactionMAnager">
 <!--Which methods are configured with transactions-->   
  <!--Configure the propagation characteristics of transactions: new  propagation-->
        <tx:attributes>
        
        <tx:method name="*"/>
        
        </tx:attributes>
    
    
 </tx:advice>


</bean>



<!--Configure transaction entry-->
<aop:config>
<aop:pointcut id="txPointCut" expression="exection(* com.zhke.mapper.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>

</aop:config>

3. Why services are needed

If transactions are not configured, there may be inconsistent data submission

If we do not configure declarative transactions in SPRING, we need to manually configure transactions in the code

Transaction is very important in the development of the project, and the consistency and integrity of data are involved in the design.

Keywords: Java

Added by Gayathri on Fri, 18 Feb 2022 15:02:12 +0200