Mybatis advanced query
– What is advanced query
- Advanced query is actually multi-condition query, we used to write query, in most cases is simple (select * from ***), but in real development, we need to query some data according to the conditions selected by users, such as when we go shopping taobao, JINGdong, We need to screen the phone -> brand -> price… These are the query conditions
- In Mybatis, advanced query is realized by our dynamic SQL, the follow-up explains what is dynamic SQL
- The following figure is actually a conditional query, title, enabled or not. If the user fills in the query criteria, we need to use dynamic SQL to do so
– What is a Query conditional object
-
When we receive conditional parameters, we can do so in two ways
-
First: use a single variable to receive a single condition. Multiple conditions can be received with multiple variables. This works for a small number of conditions, but if we have 10 conditions, 20 conditions are we going to use so many variables to receive conditions?
-
The second way is to encapsulate the query condition in our entity class. When receiving the condition and passing the condition, we only need to pass the entity class.
Note: We will receive and pass conditional objects as Query objects (the second type)
-
-
Query conditional object
- We can write an XxxQuery (Xxx is the name of the entity class or module name or table name).
Public class ArticleQuery{private String title; // Default status private Boolean enable; // Omit getter and setter methods} copy code hereCopy the code
– Mybatis dynamic SQL
-
If tags:
-
Function:
① Used to determine whether the conditions meet, meet the SPLicing SQL, do not meet the splicing
② It automatically adds Spaces to avoid SQL syntax errors
-
Note:
If the argument is a string, check for null and empty strings.
If the parameter is a numeric value, only null is required.
-
<if test='ename ! = null and !" ". The equals (ename. The trim () '> and ename like CONCAT (' %', trim (# {ename}), '%') < / if > duplicate codeCopy the code
-
Where the label
-
Function:
① Join a where
② Ignore the first redundant and or or
③ Automatically add space
-
-
Fuzzy query
# and (name like '%#{keywords}%' or password like '%#{keywords}%') And (name like '%${keywords}%' or password like '%${keywords}%') Using the concat function in mysql, the test is successful, and no SQL injection occurs. It is recommended to copy the code using and(name like concat('%',#{keywords},'%') or password like concat('%',#{keywords},'%')Copy the code
-
Special symbol handling: In SQL statements, we use some comparison symbols, and in XML we have special handling
-
Note: An error is reported in XML when special characters are not handled
-
(1) Escape characters in XML:
- ① Symbols: < [<], <= [<=], > [>], >= [>=], & [&], ‘【’, “【”】
- ② gt -> greater than lt -> less than
-
(2) Or you can use CDATA snippet:
- ① Greater than or equal to
<! [CDATA[ >= ]]>
- ② Less than or equal to
<! [CDATA[ <= ]]>
- ① Greater than or equal to
-
– Extracting SQL code blocks
< SQL id="address"> <if test='address! = null and !" ". The equals (address. The trim () '> and address like CONCAT (' %', trim (# {address}), '%') < / if > < / SQL > - use the < include > call: <include refid="address"></include> Copy codeCopy the code
- Use the advanced query TAB for advanced query testing
Why do you study Spring
– Common problems encountered in developing applications
- Problem 1: From the following code, we can find that the coupling degree between the code is too high. We need to use an interface and new its implementation class where it is used. If the interface or implementation changes, it needs to change where it is used.
- Problem 2: If there are many objects and they depend on each other, and some objects need singleton mode, while others need multiple instances, it is cumbersome to deal with.
- Problem 3: Before, we had to manually add codes to open transactions, close transactions and close connections, which would lead to bloated code and low development efficiency
Public Class EmployeeServiceImpl {// If the interface and implementation class exist in the same place, it is highly coupled and difficult to maintain. private IEmployeeDao employeeDao = new EmployeeJdbcDaoImpl(); } Duplicate codeCopy the code
Note: Spring can solve these problems
3. First acquaintance with Spring
– What is Spring
-
Spring is an open source, lightweight Inversion of Control (IOC) and AOP oriented container framework;
-
Open source: Free technology, maintained by a group of people
-
Lightweight: Compared with heavyweight (cumbersome framework design, more configuration, such as EJB (Tomcat does not support), now basically no use), development and use are relatively simple, powerful;
-
Inverse of Control-Inverse of Control: Hands over object creation rights and dependency maintenance (field assignment) to the Spring container (instead of using the old new keyword to create objects). For a specific object, it used to control other objects, but now all objects are controlled by Spring, so this is called inversion of control;
-
Spring provides a powerful IOC mechanism that helps us manage objects and maintain dependencies:
(1) Managed objects: including object creation, initialization, and destruction.
(2) Dependency maintenance: DI (Dependency Injection), which will be discussed later
Note: Classes normally managed by Spring are called beans, and objects in the Spring container are called Bean objects
-
-
AOP (Aspect Oriented Programming) : Extract the same logic, that is, separate the business logic from the application services. It then intercepts at different points in a method. Such as logging, transaction processing;
-
Container framework: Containers are things, so in Spring they are beans for managing objects.
-
Note: The underlying principles of Spring: XML + DOM4J + Factory design pattern + reflection
– Benefits of Sping framework
- Open source, free, and maintained by a regular team, active community, Java spring;
- Ease decoupling, ease maintenance, and improve development efficiency (Spring is like a big factory, it provides IOC thinking, you can leave object creation and dependency maintenance to Spring management);
- Spring supports AOP programming (Spring provides section-oriented programming, which can easily implement functions such as authorization interception and running monitoring of programs. Some common tasks such as security, transaction and log can be centrally managed, thus providing better reuse);
- Spring focuses on solutions at all layers of J2EE applications, rather than focusing on just one layer. In enterprise development, it is often used to integrate frameworks at other levels;
- Easy application testing (Spring supports junit4, which makes it easy to test Spring applications with annotations);
- Easy integration with a variety of excellent frameworks (Spring does not force applications to rely entirely on Spring, and developers are free to choose parts or all of the Spring framework and integrate with other excellent frameworks);
- Spring simplifies the use of javaEE apis (Spring provides encapsulation for some of the most difficult apis in javaEE development, such as JDBC, javaMail, remote calls, etc.);
Note: Spring’s DI mechanism reduces the complexity of business object substitution and increases decoupling between components
– Modularity of the Spring framework
- To put it simply, modularity is the organized breaking down of a large file into independent and interdependent small modules.
The functionality of the Spring framework consists of approximately 20 modules that can be grouped into:
-
(1)Core Container
- (1) Beans: responsible for the assembly of Beans in the Bean factory. The so-called Bean factory is the factory that creates objects. The assembly of Beans is also the creation of objects.
- ②Core: This module is responsible for the most basic implementation of IOC (Inversion of control);
- ③Context: The IOC container of Spring, which calls a lot of functions in Spring Core, integrates most functions of Spring. After the Bean creates the object, the Context is responsible for establishing and maintaining the bean-to-bean relationship. So you can also think of Context as a collection of Bean relationships;
- ④SpEl: Spring Expression Language;
-
(2)Data Access/Integration:
- JDBC: simple encapsulation of JDBC;
- ORM: support data integration framework encapsulation (such as Mybatis, Hibernate);
- ③OXM: Object XML Mapper, which is used to convert Java objects and XML documents back and forth;
- (4) JMS: realization of message function of producer and consumer;
- ⑤Transations: transaction management;
-
(3)Web and Remote Call:
- (1) WebSocket: provides Socket communication and push function on the Web side;
- ②Servlet: implementation of Spring MVC framework;
- ③Web: contains the core classes required by the Spring framework for Web application development, including automatically loading WebApplicationContext class, Struts integration class, file upload support class, Filter class and a large number of auxiliary tool classes;
- (4) Portlet: to achieve the aggregation of web module functions (for example, there may be different sub-windows (Portlet) under the homepage (Port) of the website);
-
(4)AOP: faceted;
-
(5)Aspects: Also an important component of aspect, providing integration of AspectJ framework;
-
(6)Instrumentation (equipment) : equivalent to a detector, to provide the JVM and Tomcat detection;
-
(7)Messaging: Spring provides the function of message processing;
-
(8)Test: When we do unit tests, Spring will help us initialize some resource objects that need to be used in the testing process.
-
Jar package for the Spring module
Introduction to Spring
– Step 1: Import the JAR package
- The first step in using the framework should be to import packages. Spring has a large number of JARS, so what packages do we need to use and what packages do we import
– Step 2: Write the core configuration file
-
Now that we have the core JAR package, based on our experience with Mybatis, we need a core configuration file at this point
-
Create an XML file under Resources. The name can be customized, but the industry name is applicationContext.xml, which is the core configuration file for Spring
-
All XML files require our header files, which are document declarations and constraints
-
You can refer to documents, both In Chinese and English;
1) spring – framework – 4.1.2. RELEASE \ docs \ spring – framework – reference \ PDF
-
Can baidu Spring configuration file;
-
You can also directly take the following content to modify
-
-
<? The 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"> <bean id="..." class="..." > <! Properties and Configuration for this bean go here --> </bean> </beans> Replicate codeCopy the code
– Step 3: Prepare common classes
- Prepare a plain Java class (MyBean) that provides a no-argument construct and prints a sentence
– Step 4: Register our own Java class into the Bean
-
Handing this class over to Spring to manage is registering it with the Spring container
- Remember, Spring is a container, and we need to leave our classes to Spring to manage. Because, our test is to create a common class, and then through Spring to help us create the object of this class is considered successful;
- Give the Java class to Spring to manage in the configuration file. Configuration in applicationContext.xml
<? The 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"> <beans ... >< bean id="myBean" class="cn.itsource._01_hello. myBean" ></bean> </beans> Copy codeCopy the code
-
Elements and attributes:
- Bean element: represents the object configuration or registration tag;
- Id attribute: the unique identity of the bean object in the Spring container. You can also use name, commonly used ID (unique attribute), which is used to fetch the object.
- Class property: Fully qualified name of the class to which the object belongs. Note that this can be a built-in class of the JDK or a new class of your own;
Note: The Spring container does not allow objects with two names (either id or name)
– Step 5: Get the Spring core object, instantiation of the Spring container
-
After we hand over our bean objects to Spring, we are sure to use them in our code, so how do we use our bean objects in Java
- Spring container objects come in two types: BeanFactory and ApplicationContext;
- ApplicationContext, which inherits from the BeanFactory interface and has more enterprise-class methods, is recommended.
– BeanFactory
- BeanFactory is an interface that implements the XmlBeanFactor class to get instantiations. The interface has a getBean() method to get configured or registered Bean objects in the Spring container;
@test public void testHelloSpring() throws Exception {** * To start the framework, you need to get Spring's core object * The first core object we'll look at is BeanFactory: As the name implies, this is a factory to create beans * and the Bean factory to create objects has to get the data from the configuration file * because: our first step is to read the configuration file, get the BeanFactory factory */ / the first step: Resource Resource = new ClassPathResource("applicationContext.xml"); BeanFactory BeanFactory = new XmlBeanFactory(resource); } Duplicate codeCopy the code
– ApplicationContext (recommended)
-
ApplicationContext, which is derived from the BeanFactory interface, contains all the functionality of the BeanFactory interface, including internationalization support, resource access (such as urls and files), event propagation, and so on. Recommended as the first choice for JavaEE applications, which can be applied in Java APP and Java Web;
-
To use the ApplicationContext functionality, you must import the appropriate JAR package:
Spring-context-4.1.2.release.jar — Context
Spring-expression – 4.1.2.release. jar — Spring expression language
// Use ApplicationContext // load the configuration file in the project classpath to instantiate String conf = "ApplicationContext. ApplicationContext factory = new ClassPathXmlApplicationContext(conf); Copy the codeCopy the code
– Gets the instance object
-
Method 1: Directly obtain the corresponding Bean object by id
// Get the object MyBean bean = (MyBean)factory.getBean(" MyBean "); System.out.println(bean); Copy the codeCopy the code
-
Method 2: Get the Bean object from the id and the object’s Class object (recommended)
MyBean = factory. GetBean (" MyBean ", mybean.class); System.out.println(bean); Copy the codeCopy the code
– ApplicationContext and BeanFactory
-
Contact:
- ApplicationContext is a subclass of BeanFactory with more functionality and methods;
-
The difference between:
- ApplicationContext by default creates Bean objects based on the configuration (immediately loaded) when the configuration file is read. BeanFactory creates objects as they are used (lazy/lazy)
-
Extension:
- When we use ApplicationContext, we can configure it to be as lazy to load as the BeanFactory, as we’ll learn later
5. Spring dependency injection
– Dependency injection concept
- IoC is an idea that focuses on dynamically providing one object with the other objects it needs while the system is running. This is achieved through DI (Dependency Injection);
- All objects in Spring are managed by Spring, but there are properties in objects that actually refer to other objects, so these objects are also managed by Spring.
- In practice, we need to assign values to the property fields of objects in Spring. This is called Dependency Injection (DI).
- Dependency injection is divided into XML injection and annotation injection.
– XML injection
- Configure in XML, but this method must have corresponding setter methods, all of which are also called property injection or setter method injection;
// Entity class package cn.itsource.test; public class MyUserBean { private String username; private String password; private MyBean myBean; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public MyBean getMyBean() { return myBean; } public void setMyBean(MyBean myBean) { this.myBean = myBean; } @Override public String toString() { return "MyUserBean [username=" + username + ", password=" + password + ", myBean=" + myBean + "]"; }} Copy the codeCopy the code
<! - the core configuration file injection - > < bean id = "myUserBean" class = "cn. Itsource. Test. MyUserBean" > <! -- name is to inject properties into the bean object, <property name="username" value=" username" ></property> <property name="password" value="123456"></property> <! -- name specifies the bean object to be injected with the property, ref specifies the bean object to be injected with the property value, <property name="myBean" ref=" myBean" ></property> </bean> copy codeCopy the code
// Test @org.junit.Test public void testGetMyUserBean() throws Exception {ApplicationContext ApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); MyUserBean bean = applicationContext.getBean("myUserBean", MyUserBean.class); System.out.println(bean); } Duplicate codeCopy the code
Note: XML injection must provide a set method for attributes, otherwise an error will be reported
– Annotation injection:
- Injection via annotations, you can write annotations on setter methods, you can write annotations on fields, if you write on fields you don’t need setter methods, if you want annotation injection to succeed, you need full annotations;
– use the @autowired
- the @autowired annotation for the Spring, you need to import the package org. Springframework. Beans. Factory. The annotation. Autowired; - @qualifier: Specifies the Bean name replication codeCopy the code
package cn.itsource.test; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; public class MyUserBean { private String username; private String password; // @autowired will inject the value of the field automatically if it matches the type. @autowired @Qualifier("myBean") private myBean myBean; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public MyBean getMyBean() { return myBean; } @Override public String toString() { return "MyUserBean [username=" + username + ", password=" + password + ", myBean=" + myBean + "]"; }} // XML configuration: <bean id="date" class="java.util.Date"></bean> <bean id="mybean" class="cn.itsource.test.MyBean"></bean> <bean Id = "myUserBean" class = "cn. Itsource. Test. MyUserBean" > < property name = "username" value = "zhang SAN" > < / property > < property name="password" value="123456"></property> <! Name is the name of the bean to be injected into the property, ref is the value of the property to be injected into the bean, is the id of the bean we gave spring to manage --> <! -- <property name="myBean" ref=" myBean"Copy the code
– use the @ the Resource
- @ the Resource provided by J2EE, you need to import the package javax.mail. The annotation. The Resource, Spring supports the annotation
- Name property: Specifies the name of the Bean
package cn.itsource.test; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; public class MyUserBean { private String username; private String password; // @autowired will inject the value of the field automatically if it matches the type. // @autowired // @Qualifier("myBean") // private myBean myBean; @resource Private MyBean MyBean; @resource private MyBean; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public MyBean getMyBean() { return myBean; } @Override public String toString() { return "MyUserBean [username=" + username + ", password=" + password + ", myBean=" + myBean + "]"; }} Copy the codeCopy the code
Note: When instantiating beans and injecting Bean objects, do not mix XML and annotations. Either use XML (today) or annotations (use spring tests or sproingMVC to fully annotate beans).
Vi. Spring testing
– Introduction to Spring testing
- Unit testing plays an important role in our software development process;
- And now that Spring has become standard for Java-based enterprise applications, how can you better use unit testing in the Spring framework?
- The Spring framework provides great support for unit testing (junit4), so you don’t have to use traditional unit tests to test Spring functionality. Through SpringJunit testing, annotations are used to help us read configuration files and assign values, simplifying testing code and improving testing efficiency;
– Advantages of Spring testing
- When the three frameworks are integrated, if the Spring configuration file cannot be read, the whole project will not run. Spring testing allows us to use annotations to read the corresponding configuration file and run the project without starting the server.
– Spring test steps
-
Import the JAR packages required for Spring testing
RELEASE. Jar -- test package -- spring -- aop-4.1.2.release. Jar --AOP package copy codeCopy the code
Note: The test package relies on AOP, so you need to import the AOP JAR package. If you do not import it, an error will be reported
-
Write common test classes and test methods
-
Add two annotations to the test class method
-
@ RunWith (SpringJUnit4ClassRunner. Class) : it means start the Spring container, put the junit to run in the Spring container; – SpringJUnit4ClassRunner: indicates the test environment of Junit4
-
@ ContextConfiguration (” classpath: applicationContext. XML “) : from the classpath path to load the resource files;
- classpath: finds the configuration file to copy the code from the project directoryCopy the code
-
Note: If you do not write classpath, the default is to find the corresponding configuration file in the flat path of the test class. If you write @contextConfiguration without the classpath& configuration file name, the default is to find the configuration file named test class name-context.xml in the horizontal path of the test class.
Spring configuration details
– Scope of the Bean object
-
Scope refers to whether our Bean object is singleton or multi-instance
-
Spring uses the singleton pattern by default, and we get an object no matter how many times we fetch a Bean object
-
Change the Bean object default scope
-
In a Bean object, we can change it through the Scope property
- Singleton: Default, singleton
- Prototype: more cases
-
MyScopeBean" scope="prototype"></bean> Copy codeCopy the code
Other attribute values: Generally not used
– Bean object configuration lazy loading
- We already know that our ApplicationContext gets the bean to be loaded urgently, so how do we make it lazily loaded
- One of two ways
- Add default-lazy-init to the root object of the configuration file and set it to true
<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 "default - lazy - init =" true "> < / beans > duplicate codeCopy the code
- Second: lazy/lazy loading of a single Bean object
</bean id="user" class="cn.itdemo.test. user" lazy-init="true"></bean> Copy codeCopy the code
– The life cycle of the Bean object
-
Beans with different scopes have different life cycles:
-
Spring-managed Bean objects are singletons by default;
-
Instantiation and initialization of Bean objects:
- Instantiation is essentially the Spring container calling the Bean’s no-argument construct to create the Bean object;
- Initialization is essentially the Spring container calling the specified initialization method;
-
Beanfactory-managed beans create Bean objects when they are used by default, lazy loading. Appliacationcontext-managed beans create Bean objects when the container is created by default, urgent loading.
-
Bean object destruction:
- Essentially, the Spring container calls the specified destruction method (not really destroying the Bean object);
- When the container is closed (ApplicationContext does not have a close method; its implementation class does), the Spring container automatically calls the specified destruction method.
-
-
Initialization and destruction methods can be specified through the init-method and destroy-method attributes of the bean element. But we generally don’t configure this life cycle ourselves. This is basically used by Spring itself, for example, when Spring operates on connection pooling. It is executed when a DateSource is destroyed;
- This is the end of Mybatis Advanced Query & Spring foundation