1,Spring
1.1 INTRODUCTION
The spring framework was created due to the complexity of software development. Spring uses basic JavaBean s to accomplish things that could only be done by EJB s before. However, the use of spring is not limited to server-side development. In terms of simplicity, testability and loose coupling, most Java applications can benefit from spring.
- Spring concept: the existing technology is easier to use. It is a hodgepodge and integrates the existing technology framework
- SSH : Struct2+Spring+Hibernate
- SSM: SprMVC+Spring+Mybatis
1.2 advantages
- Spring is an open source free framework (container)
- Spring is a lightweight, non intrusive framework
- Inversion of control (IOC), aspect oriented programming (AOP)!
- Support transaction processing and framework integration!
Spring is a lightweight inversion of control (IOC) and aspect oriented programming (AOP) framework!
1.3 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-YZIqWxZ4-1652524609583)(D:\Desktop \ learning notes \ image \ image-20220510150011761.png)]
1.4 expansion
Modern java development is Spring based development!
[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-cjUFaAy7-1652524609584)(D:\Desktop \ learning notes \ image \ image-20220510150319012.png)]
- Spring Boot
- A rapidly developed scaffold
- Based on SpringBoot, you can quickly develop a single micro service.
- Contract greater than configuration
- Spring Cloud
- Spring cloud is implemented based on SpringBoot
Now most companies are using SpringBoot for rapid development. The premise of learning SpringBoot is to fully master Spring and Spring MVC!
Disadvantages: the configuration is too cumbersome, known as "configuration hell"
2. IOC theoretical derivation
Example:
The essence of user operating the database is to call the Dao layer by calling the service layer, so users only need to call the methods of the service layer to operate the database
[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-ZrBV1ybu-1652524609586)(D:\Desktop \ learning notes \ image \ image-20220510154605949.png)]
UserServiceImpl:
package com.cjp.service; import com.cjp.dao.UserDao; import com.cjp.dao.UserDaoImpl; public class UserServiceImpl implements UserService{ private UserDao userDao = new UserDaoImpl(); @Override public void getUserService() { userDao.getUser(); } }
Analysis: at this time, userdao in UserServiceImpl is fixed. When there are multiple implementation classes of userdao interface and users need to use different implementations, they need to modify the source code of UserServiceImpl.
Optimized UserServiceImpl:
package com.cjp.service; import com.cjp.dao.UserDao; public class UserServiceImpl implements UserService{ private UserDao userDao; public UserServiceImpl(UserDao userDao) { this.userDao = userDao; } @Override public void getUserService() { userDao.getUser(); } }
Analysis: the UserDao in the modified UserServiceImpl is not determined, but is created through the constructor.
Before and after comparison:
- Before, the program took the initiative to create objects, and the control was in the hands of the programmer!
- After using set injection, the program no longer has the initiative, the control is in the user, and the program passively accepts the object!
This idea essentially solves the problem. When users have different needs, they do not need to modify the source code, reduce the system coupling, and can focus more on the implementation of business! This is the prototype of IOC!
IOC essence
Inversion of control (IoC) is a design idea. DI (dependency injection) is a method to realize IoC. Some people think that DI is just another way of saying IoC. In programs without IoC, we use object-oriented programming. The creation of objects and the dependencies between objects are completely hard coded. In programs, the creation of objects is controlled by the program itself. After the control is reversed, the creation of objects is transferred to a third party. Personally, I think the so-called control reversal is the reversal of the way to obtain dependent objects.
When configuring beans in XML, the definition information of beans is separated from the implementation, and the annotation method can integrate the two. The definition information of beans is directly defined in the implementation class in the form of annotation, so as to achieve the purpose of zero configuration.
Inversion of control is a way to produce or obtain specific objects through description (XML or annotation) and through a third party. In Spring, the IoC container implements control inversion, and its implementation method is dependency injection (DI).
3,HelloSpring
1. Create an entity class Hello:
package com.cjp.pojo; public class Hello { private String string; public String getString() { return string; } public void setString(String string) { this.string = string; } @Override public String toString() { return "Hello{" + "string='" + string + '\'' + '}'; } }
2. Create a new configuration file beans. Under resource 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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="hello" class="com.cjp.pojo.Hello"> <property name="string" value="Spring"/> </bean> </beans>
3. Test
import com.cjp.pojo.Hello; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Hello hello = (Hello) context.getBean("hello"); System.out.println(hello); } }
4. How IOC creates objects
1. Use parameterless construction to create objects. Default!
2. Suppose we want to create an object using a parametric construct.
-
Subscript assignment
<bean id="user" class="com.cjp.pojo.User"> <constructor-arg index="0" value="cjp"/> </bean>
-
type assignment
<bean id="user" class="com.cjp.pojo.User"> <constructor-arg type="java.lang.String" value="cjp"/> </bean>
-
Set directly by parameter name
<bean id="user" class="com.cjp.pojo.User"> <constructor-arg name="name" value="cjp"/> </bean>
Summary: when the configuration file is loaded, the objects registered in the container have been initialized
5. Spring configuration
- alias
<alias name="user" alias="newUser"/>
After setting the alias, you can also use the alias to get the object.
- Bean configuration
id: bean The unique identifier of the object, which is equivalent to the object name class: bean Fully qualified name corresponding to the object: package name+Class name name: It's also an alias, and name Multiple aliases can be set at the same time, separated by commas, spaces, semicolons, etc
- import
When the team develops, multiple beans configuration files are created. Import can be used to import and merge multiple configuration files into one
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <import resource="beans.xml"/> <import resource="beans1.xml"/> <import resource="beans2.xml"/> <import resource="beans3.xml"/> </beans>
6. Dependency injection
6.1. Constructor injection
Injecting attributes using constructors
6.2 set mode injection (key)
- Dependency injection: set injection!
- Dependency: the creation of bean objects depends on the container
- Injection: all properties in the bean object are injected by the container!
Build environment
1. Create a complex entity class:
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; //getter setter toString method omitted
package com.cjp.pojo; public class Address { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
2.beans.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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="address" class="com.cjp.pojo.Address"> <property name="address" value="Yuelu District, Changsha City, Hunan Province"/> </bean> <bean id="student" class="com.cjp.pojo.Student"> <!--Ordinary injection--> <property name="name" value="cjp"/> <!--bean injection--> <property name="address" ref="address"/> <!--Array injection--> <property name="books"> <array> <value><Principles of computer composition</value> <value><Operating system</value> <value><Compilation principles</value> <value><Computer network</value> </array> </property> <!--List injection--> <property name="hobbys"> <list> <value>sing</value> <value>jump</value> <value>rap</value> <value>Basketball</value> </list> </property> <!--Map injection--> <property name="card"> <map> <entry key="meal card" value="12143432"/> <entry key="Campus card" value="2435657"/> <entry key="bank card" value="3943759536784"/> </map> </property> <!--Set injection--> <property name="games"> <set> <value>Original God</value> <value>Glory of Kings</value> <value>Naruto</value> </set> </property> <!--null injection--> <property name="wife"> <null/> </property> <!--properties injection--> <property name="info"> <props> <prop key="Student number">20192712</prop> <prop key="class">Landscape architecture class 2</prop> <prop key="height">183cm</prop> </props> </property> </bean> </beans>
3. Test
import com.cjp.pojo.Student; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Student student = (Student) context.getBean("student"); System.out.println(student); } /*Student{ name='cjp', address=Address{address='Yuelu District, Changsha City, Hunan Province '}, books=[<Computer composition principle, operating system, compilation principle, computer network], hobbys=[Sing, dance, rap, basketball], card={Meal card = 12143432, campus card = 2435657, bank card = 3943759536784}, games=[Original God, King glory, Naruto], wife='null', info={Student number = 20192712, class = landscape architecture class 2, height = 183cm}} */ }
6.3. Expansion mode injection
- P namespace and C namespace
<?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:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user" class="com.cjp.pojo.User" p:age="18" p:name="cjp"/> <bean id="user2" class="com.cjp.pojo.User" c:name="aas" c:age="10"/> </beans>
be careful:
1. The P namespace and c namespace cannot be used directly. xml constraints need to be imported
2.p no parameter structure is required for naming
3.c naming requires structure
6.4 scope of bean
1. Singleton mode (Spring default)
<bean id="user2" class="com.cjp.pojo.User" c:name="aas" c:age="10" scope="singleton"/>
2. Prototype pattern: every time you get from the container, a new object will be generated!
<bean id="user2" class="com.cjp.pojo.User" c:name="aas" c:age="10" scope="prototype"/>
3,request,session,application
Only used in web development!
7. Automatic assembly of Bean
- Automatic assembly is a way for Spring to meet bean dependencies
- Spring will automatically search in the context and automatically assemble properties for bean!
Three assembly methods:
- Display configuration in xml
- Display configuration in Java
- Implicit automatic assembly bean [important]
7.1 test
1. Build environment
One person has two pets!
- ByName
<!--bean id To correspond to the property name of the class to be automatically assembled--> <bean id="cat" class="com.cjp.pojo.Cat" ></bean> <bean id="dog" class="com.cjp.pojo.Dog" ></bean> <bean id="person" class="com.cjp.pojo.Person" autowire="byName" > <property name="name" value="cjp"/> </bean>
- ByType
<!--bean id It is OK not to correspond to the type corresponding to the attribute name of the class to be assembled automatically--> <bean id="ca" class="com.cjp.pojo.Cat" ></bean> <bean id="do" class="com.cjp.pojo.Dog" ></bean> <bean id="person" class="com.cjp.pojo.Person" autowire="byType" > <property name="name" value="cjp"/> </bean>
- Automatic assembly using annotations
1. Import constraints
2. Configuration annotation support
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--Enable annotation support--> <context:annotation-config/> </beans>
3.@Autowired
When the bean type in the container uniquely corresponds to the Person class attribute, you can just use @ Autowired
@Autowired can be used on entity class attributes or setter methods; After using on the property, you don't need to write setter method.
Person:
public class Person { @Autowired private Dog dog; @Autowired private Cat cat; private String name; //getter setter method omitted }
beans.xml:
<bean id="cat" class="com.cjp.pojo.Cat" ></bean> <bean id="dog" class="com.cjp.pojo.Dog" ></bean> <bean id="person" class="com.cjp.pojo.Person" />
4.@Qualifier
When there is only one instance of @ wi injected into the same container, it is impossible
You also need to use @ Qualifier to specify the instance name to be injected
<bean id="cat111" class="com.cjp.pojo.Cat" ></bean> <bean id="cat11" class="com.cjp.pojo.Cat" ></bean> <bean id="dog111" class="com.cjp.pojo.Dog" ></bean> <bean id="dog11" class="com.cjp.pojo.Dog" ></bean> <bean id="person" class="com.cjp.pojo.Person" />
public class Person { @Autowired @Qualifier(value = "dog11") private Dog dog; @Autowired @Qualifier(value = "cat111") private Cat cat; private String name; }
5.@Resource
public class Person { @Resource(name = "dog11") private Dog dog; @Resource(name = "cat111") private Cat cat; private String name; }
Summary:
@Difference between Resource and @ Autowired:
- They are used for automatic assembly and can be placed in the attribute field
- @Autowired is implemented by ByType
- @Resource is implemented by ByName by default. If the name cannot be found, it is implemented by ByType. If both cannot be found, an error will be reported!
- Different execution order: @ Autowired is implemented by ByType.
8. Using annotation development
In spring 4
After that, if you develop with annotations, you must ensure that the AOP package is imported.
To use annotations, you need to import context constraints and add annotation support.
1,bean
-
Import constraints
<context:component-scan base-package="com.cjp.pojo"/>
-
Using annotations
package com.cjp.pojo; import org.springframework.stereotype.Component; //Equivalent to < bean id = "user" class = "com. CJP. POJO. User" / > @Component public class User { public String name="cjp"; }
2. How to inject attributes
@Component public class User { /* Equivalent to < bean id = "user" class = "com. CJP. POJO. User" > <property name="name" value="cjp"/> </bean>*/ @Value("cjp") public String name; }
3. Derived annotation
@Component has several derived annotations. In web development, we will layer according to MVC three-tier architecture!
- dao [@Repository]
- service [@Service]
- controller [@Controller]
The functions of these four annotations are the same. They all register a class in the Spring container!
4. Automatic assembly
@Autowired:Automatic assembly by name and type provided that 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 and type
5. Scope
@Scope("prototype") public class User { /* Equivalent to < bean id = "user" class = "com. CJP. POJO. User" > <property name="name" value="cjp"/> </bean>*/ @Value("cjp") public String name; }
6. Summary
xml and annotations:
- xml is more versatile and suitable for any occasion! Simple maintenance
- Annotations are not their own classes and cannot be used. Maintenance is relatively complex
Best practices for xml and annotations:
- xml is used to manage bean s;
- Annotation is only responsible for completing attribute injection;
- In the process of using, we should pay attention to enabling annotation support
9. Configure Spring using java
Use java configuration classes instead of xml configuration files.
JavaConfig is a sub project of Spring. After Spring 4, it has become a core function!
1. Entity class
package com.cjp.pojo; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; //This indicates that this class is taken over by Spring and registered in the container @Component public class User { //Injection attribute @Value("cjp") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }
2. Configure class MyConfig
package com.cjp.config; import com.cjp.pojo.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration//Represents that this is a configuration class, equivalent to beans xml //This will also be hosted by the Spring container and registered in the container, because it is originally a @ Component @ComponentScan("com.cjp.pojo") @Import(MyConfig2.class) //Import other configuration classes public class MyConfig { /*Equivalent to beans bean tags in XML * The method name is equivalent to the id in the tag * The return value of the method is equivalent to the class in the tag*/ @Bean public User getUser(){ return new User();//Returns the object to be injected into the bean } }
3. Testing
import com.cjp.config.MyConfig; import com.cjp.pojo.User; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class MyTest { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class); User getUser = context.getBean("getUser", User.class); System.out.println(getUser.getName()); } }
This pure java configuration method can be seen everywhere in SpringBoot!
10. Agent mode
Proxy mode is the bottom layer of spring AOP!
Classification mode of agent:
- Static proxy
Real role
proxy role
Client
-
Dynamic agent
- The dynamic proxy role is the same as the static proxy role
- The agent class of dynamic agent is generated dynamically, which is not written directly
- Dynamic agents are divided into two categories: interface based dynamic agents and class based dynamic agents
- Interface based: JDK dynamic agent [we use here]
- Class based: Cglib
- java bytecode implementation: JAVAsist
1. Interface
package com.cjp.demo01; public interface Rent { public void rent(); }
2. Real role
package com.cjp.demo01; public class Host implements Rent{ @Override public void rent() { System.out.println("The landlord rents the house!"); } }
3. Tool class for generating dynamic proxy class
package com.cjp.demo01; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyInvokeHandler implements InvocationHandler { //Proxy interface private Object target; public void setRent(Object target) { this.target = target; } //Generated proxy class public Object getProxy(){ return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this); } //Process the proxy instance and return the result @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = method.invoke(target, args); return result; } }
4. Testing
package com.cjp.demo01; import java.lang.reflect.Proxy; public class Client { public static void main(String[] args) { Host host = new Host();//Real role ProxyInvokeHandler pih = new ProxyInvokeHandler(); pih.setRent(host); Rent proxy = (Rent) pih.getProxy(); proxy.rent(); } }
The dynamic proxy class represents an interface, so it can proxy multiple implementation classes. You only need to modify the injected implementation class
11.AOP implementation
Import dependency
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency>
Method 1: use Spring API interface [mainly Spring API interface implementation]
1. Interface
2. Interface implementation class
3. Log class
package com.cjp.log; import org.springframework.aop.AfterReturningAdvice; import java.lang.reflect.Method; public class After implements AfterReturningAdvice { @Override public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable { System.out.println("Used"+method.getName()+"Method, the return value is:"+o); } }
package com.cjp.log; import org.springframework.aop.MethodBeforeAdvice; import java.lang.reflect.Method; public class Before implements MethodBeforeAdvice { @Override public void before(Method method, Object[] objects, Object o) throws Throwable { System.out.println("Used"+o.getClass().getName()+"Class"+method.getName()+"method"); } }
4.beans configuration file
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="userService" class="com.cjp.service.UserServiceImpl"/> <bean id="before" class="com.cjp.log.Before"/> <bean id="after" class="com.cjp.log.After"/> <aop:config> <aop:pointcut id="pointcut" expression="execution(* com.cjp.service.UserServiceImpl.*(..))"/> <aop:advisor advice-ref="after" pointcut-ref="pointcut"/> <aop:advisor advice-ref="before" pointcut-ref="pointcut"/> </aop:config> </beans>
5. Test
import com.cjp.service.UserService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService = (UserService) context.getBean("userService"); userService.select(); } }
[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-iokBA2bX-1652524609588)(D:\Desktop \ learning notes \ image \ image-20220511174555953.png)]
Method 2: use custom classes to implement AOP [mainly section definition]
Customize a class:
package com.cjp.diy; public class DiyAdvance { public void before(){ System.out.println("========Before method execution========"); } public void after(){ System.out.println("========After method execution========"); } }
to configure:
<!--Mode 2:--> <bean id="userService" class="com.cjp.service.UserServiceImpl"/> <bean id="diy" class="com.cjp.diy.DiyAdvance"/> <aop:config> <!--Custom section--> <aop:aspect ref="diy"> <!--breakthrough point--> <aop:pointcut id="point" expression="execution(* com.cjp.service.UserServiceImpl.*(..))"/> <!--notice--> <aop:before method="before" pointcut-ref="point"/> <aop:after method="after" pointcut-ref="point"/> </aop:aspect> </aop:config>
Method 3: implement with annotation
Create a new section class:
package com.cjp.diy; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class AnnotationAspect { @Before("execution(* com.cjp.service.UserServiceImpl.*(..))") public void before(){ System.out.println("=====Before method execution======"); } @After("execution(* com.cjp.service.UserServiceImpl.*(..))") public void after(){ System.out.println("=====After method execution======"); } @Around("execution(* com.cjp.service.UserServiceImpl.*(..))") public void around(ProceedingJoinPoint pj) throws Throwable { System.out.println("Surround front"); Signature signature = pj.getSignature();//Get signature System.out.println(signature); Object proceed = pj.proceed();//Execution method System.out.println("After surround"); } }
to configure:
<!--register bean--> <bean id="userService" class="com.cjp.service.UserServiceImpl"/> <bean id="aspect" class="com.cjp.diy.AnnotationAspect"/> <!--Enable annotation support--> <aop:aspectj-autoproxy/>
12. Integrate Mybatis
Steps:
1. Import dependency
- junit
- mybatis
- mysql database
- spring related
- aop implantation
- mybatis-spring
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.0.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> </dependency> </dependencies>
2. Prepare configuration file
3. Test
12.1. Recall Mybatis
1. Writing entity classes
2. Write core configuration file
3. Write interface
4. Write mapper xml
5. Testing
12.2,Mybatis-spring
1. Write data source configuration
2.sqlSessionFactory
3.sqlSession
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--use Spring Data source replacement for mybatis Configuration of c3p0 dbcp druid Here we use Spring Provided JDBC--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <!--sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!--binding Mybatis configuration file--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath:com/cjp/mapper/UserMapper.xml"/> </bean> <!--sqlSession--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--Only constructor injection can be used because it does not setter method--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> <bean id="userMapper" class="com.cjp.mapper.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean> </beans>
4. You need to add an implementation class to the interface
Mode 1:
package com.cjp.mapper; import com.cjp.pojo.User; import org.mybatis.spring.SqlSessionTemplate; import java.util.List; public class UserMapperImpl implements UserMapper{ private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } @Override public List<User> getUsers() { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.getUsers(); } }
Mode 2:
package com.cjp.mapper; import com.cjp.pojo.User; import org.mybatis.spring.support.SqlSessionDaoSupport; import java.util.List; public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{ @Override public List<User> getUsers() { return getSqlSession().getMapper(UserMapper.class).getUsers(); } }
to configure:
<bean id="userList" class="com.cjp.mapper.UserMapperImpl2"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>
5. Inject the implementation class written by yourself into Spring
6. Test use
@Test public void test() throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml"); UserMapperImpl userMapper = context.getBean("userMapper", UserMapperImpl.class); List<User> users = userMapper.getUsers(); for (User user : users) { System.out.println(user); } }
13. Declarative transaction
1. Review transaction
- Treat a group of businesses as a business, and they will either succeed or fail
- Transaction is very important in project development. It involves the consistency of data and cannot be careless
- Ensure integrity and consistency;
ACID principle of transaction:
- Atomicity
- uniformity
- Isolation
- Multiple businesses may operate one 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 transaction: it is necessary to manage the transaction in the code
1. Build environment
Introducing transaction constraints
Interface:
package com.cjp.mapper; import com.cjp.pojo.User; import org.apache.ibatis.annotations.Param; import java.util.List; public interface UserMapper { List<User> getUsers(); /*Insert a user*/ int addUser(User user); /*Delete a user*/ int delete(int id); }
UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.cjp.mapper.UserMapper"> <select id="getUsers" resultType="user"> select * from mybatis.user </select> <insert id="addUser" parameterType="user"> insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd}) </insert> <!--Deliberately delete Misspelling--> <delete id="delete" parameterType="_int"> deletes from mybatis.user where id=#{id} </delete> </mapper>
Implementation class:
package com.cjp.mapper; import com.cjp.pojo.User; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.support.SqlSessionDaoSupport; import java.util.List; public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{ @Override public List<User> getUsers() { User user = new User(1007, "Delireba", "535321"); addUser(user); delete(1006); return getSqlSession().getMapper(UserMapper.class).getUsers(); } @Override public int addUser(User user) { return getSqlSession().getMapper(UserMapper.class).addUser(user); } @Override public int delete(int id) { return getSqlSession().getMapper(UserMapper.class).delete(id); } }
Running result: Although an error is reported, the user is still inserted into the database
2. Configuration transactions
<!--Configure declarative transactions--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--combination AOP Implement transaction implantation--> <!--Configure transaction notifications--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!--Which methods are configured with transactions--> <!--Configure propagation properties of transactions propagation--> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!--Configure transaction entry--> <aop:config> <aop:pointcut id="point" expression="execution(* com.cjp.mapper.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="point"/> </aop:config>
Running result: as long as an error is reported, the database will not be changed