The Spring parts:

1. Seven modules of the Spring Framework:

Spring Core: The most basic part of the framework, which provides an IoC container for managing beans.

Spring Context: Inherits BeanFactory, provides Context information, extends JNDI, EJB, email, internationalization, and more.

Spring DAO: Provides a JDBC abstraction layer and a declarative transaction management approach.

Spring ORM: Provides JPA, JDO, Hibernate, MyBatis and other ORM mapping layers.

Spring AOP: Integrates all AOP capabilities.

Spring Web: Provides context information for basic Web development, and existing Web frameworks, such as JSF, Tapestry, Structs, and so on, provide integration.

Spring Web MVC: Provides a fully functional implementation of model-View-Controller for Web applications.

Beans define five scopes:

Singleton: A unique bean instance. Beans in Spring are singleton by default.

Prototype: Each request creates a new bean instance.

Request: Each HTTP request generates a new bean that is valid only within the current HTTP Request.

Session: Each HTTP request generates a new bean that is valid only for the current HTTP session.

Global-session: the global session scope, which is only meaningful in portlet-based web applications, is no longer available in Spring5. Portlets are small Java Web plug-ins that can generate snippets of semantic code, such as HTML. They are based on portlet containers and can handle HTTP requests like servlets. However, unlike servlets, each portlet has a different session.

Spring IOC initialization process:

1. Resource location: find user-defined bean resources, and load beanDefinition by ResourceLoader through the unified interface Resource interface.

BeanDefinitionReader Reads resources defined by resources and loads them into ioc as BeanDefinitions (maintained by HashMap for BD).

3. Beandefinitions registration means registering these BeanDefinitions with the IOC container, which is implemented by BeanDefinitionRegistery. BeanDefinition loading process: define BeanDefinitionReader parsing XML document BeanDefinitionDocumentReader parsing the document into a BeanDefinition

DI dependency injection process? ** (instantiate, handle dependencies between beans)

Procedure After Ioc initialization, the dependency injection process is triggered the first time a user requests a Bean from the Ioc container

If lazy-init=true, the singleton bean will be initialized on the first getBean. If lazy-init=false, the singleton bean will be initialized on container startup.

Beanfactory.getbean (); beanfactory.getBean ();

3. Beans generated using the decorator pattern are beanWrapper (bean enhancements);

Do you understand the thread-safety issues of singleton beans in Spring?

Most of the time we don’t use multithreading in our systems, so few people pay attention to it. Singleton beans have threading problems, mainly because of thread-safe writes to non-static member variables of an object when multiple threads are working on the same object. There are two common solutions:

1. Try to avoid defining mutable member variables in Bean objects (impractical).

2. Define a ThreadLocal member variable in the class and store the required variable member variables in the ThreadLocal (recommended).

How does dependency injection handle dependencies between beans?

This is done by using placeholders when beanDefinition is loaded if the bean has a dependency. When getBean is called, if a placeholder is encountered, the bean is fetched from ioc and injected into this instance.

Bean life cycle:

1. Instantiate the Bean

2. Configure the instantiated Bean according to the Spring context — that is, IOC injection

3. If the Bean already implements the BeanNameAware interface, its implemented setBeanName(String) method is called, passing in the Bean ID value from the Spring configuration file.

4. If the Bean already implements the BeanFactoryAware interface, its implementation of setBeanFactory is called (setBeanFactory(BeanFactory) passes the Spring factory itself. Simply configure a normal Bean in the Spring configuration file.)

5. If the Bean already implements the ApplicationContextAware interface, the setApplicationContext(ApplicationContext) method is called, passing in the Spring context. But it’s better than 4 because ApplicationContext is a subinterface of the BeanFactory and has more implementation methods).

6, if the Bean associated the BeanPostProcessor interface, will call postProcessBeforeInitialization (Object obj, String s) method, BeanPostProcessor is often used as a change to the Bean content, and since this is a method that calls that at the end of Bean initialization, it can also be applied to memory or caching techniques;

7. If the Bean has the init-method property configured in the Spring configuration file, it automatically calls its configured initialization method.

8, if the Bean associated the BeanPostProcessor interface, will call postProcessAfterInitialization (Object obj, String s) method. Note: After the above work is done, we can apply the Bean, which is a Singleton, so normally we will call the Bean with the same ID on the instance with the same content address. Of course, we can also configure the non-Singleton in the Spring configuration file, so we won’t go into details here.

9. When the Bean is no longer needed, it passes through the DisposableBean stage. If the Bean implements the interface DisposableBean, its implementation destroy() method will be called;

10. Finally, if the Bean has the destroy-method property configured in its Spring configuration, its configured destruction method is automatically called. Juejin. Cn/post / 684490…

IOC: Inversion of control

Spring manages the creation of objects. DI (dependency injection) : When Spring creates an object, it injects the properties that the object depends on into the class.

Spring’s IOC injection approach

Constructor injection setter methods inject annotation injection interface injection

How do I detect circular dependencies?

The Bean can be marked at creation time, and if the recursive call comes back and finds that the Bean is being created, it indicates that the loop is dependent.

How does Spring solve the Bean loop dependency problem?

Spring has loop dependency scenarios: constructor loop dependency, property loop dependency

SingletonObjects: the first level cache, which holds instantiated singletonObjects;

EarlySingletonObjects: the second level cache, which holds pre-exposed singleton objects;

SingletonFactories: The third-level cache that holds object factories of objects to be instantiated. Spring first fetches beans from the level-1 cache singletonObjects when they are created. If not, and the object is being created, then it is fetched from the earlySingletonObjects cache, or from the singletonFactories cache (after the Bean calls the constructor to instantiate, even if the properties are not filled, The object can be located in the heap according to the object reference, which is based on the principle of Java reference passing), and then moved from the level 3 cache to the level 2 cache. After it is fully initialized, it can be put into the level 1 cache for other use. Because the constructor is executed before the singletonFactories level 3 cache is added, the constructor’s loop dependency cannot be resolved.

Constructor cyclic dependency workaround:

Use the @lazy annotation in the constructor for Lazy loading. When a dependency is injected, the proxy object is injected first, and then the object is created when it is used for the first time.

What design patterns are used in Spring?

Factory pattern: Spring’s BeanFactory is an example of the simple factory pattern, passing in unique identifiers to get bean objects;

Singleton pattern: provides a global access point BeanFactory;

Proxy mode: The principle of AOP functionality is to use proxy mode (1, JDK dynamic proxy. 2. CGLib bytecode generation technology agent.

Decorator mode: Dependency injection requires BeanWrapper;

Observer pattern: A common place in Spring for the Observer pattern is the listener implementation. Such as ApplicationListener.

Policy pattern: Bean instantiation determines how the Bean instance is initialized (reflection or CGLIB dynamic bytecode generation)

AOP core Concepts

1. Aspect: A class is an abstraction of object features, while a section is an abstraction of crosscutting concerns

2. Crosscutting concerns: which methods to intercept and how to deal with them are called crosscutting concerns.

Joinpoint: intercepted point. Since Spring only supports method type join points, join points in Spring refer to intercepted methods. In fact, join points can also be fields or constructors.

4. Pointcut: Definition of interception of join points

Advice: Advice refers to the code to be executed after intercepting the join point. Advice can be divided into five categories: pre, post, exception, final, and surround advice.

6. Target object: The target object of the proxy

7. Weave: The process of applying facets to the target object and causing the proxy object to be created

Introduction: An introduction can dynamically add methods or fields to a class at run time without modifying the code.

Explain AOP

Traditional oop development code logic from the top down, the process will produce some cross-cutting issues, our main business logic relation with these problems, will be scattered in various parts of the code, difficult to maintain, aop idea is to separate the business logic and the problem of crosscutting, achieve the goal of decoupling, enhance code reusability and development efficiency;

The main application scenarios of AOP include logging, performance monitoring, permission control and transaction management

AOP source code analysis:

@ EnableAspectJAutoProxy to container (the beanFactory) registered in a AnnotationAwareAspectJAutoProxyCreator object;

AnnotationAwareAspectJAutoProxyCreator proxy objects created on the target object, the object is encapsulated JDK and additional two technology, realize the dynamic proxy objects created (in the process of creating a proxy object will create a proxy factory first, Get all the enhancers (notification methods), inject these enhancers and target classes into the proxy factory, and then use the proxy factory to create objects);

The proxy object executes the target method, obtains the interceptor chain of the target method, and uses the chain mechanism of the interceptor to enter each interceptor in turn for execution.

Which dynamic proxy does AOP use?

When an interface or a subclass of Proxy exists in the bean implementation, use the JDK dynamic Proxy.

There is no interface and Spring uses CGLIB to generate proxy objects.

JDK dynamic proxies mainly involve two classes in the java.lang.Reflect package: Proxy and InvocationHandler. Proxy uses the InvocationHandler interface (which defines crosscutting logic) to dynamically create Proxy objects for the target class.

What is the difference between Spring AOP and AspectJ AOP?

Spring AOP is runtime enhancement, while AspectJ is compile-time enhancement.

Spring AOP is based on Proxying, while AspectJ is based on Bytecode Manipulation.

Spring AOP already integrates with AspectJ, which is arguably the most complete AOP framework in the Java ecosystem.

AspectJ is more powerful than Spring AOP, but Spring AOP is relatively simple, and if we have fewer facets, there is not much difference in performance. However, when there are too many facets, AspectJ is the best choice, which is much faster than Spring AOP.

JDK dynamic proxy:

Bind is used to establish the relationship between the Proxy and the real object, and proxy.newProxyInstance (target) is used to generate the Proxy object. Proxy objects implement methods that call real objects by reflecting the Invoke method.

Dynamic proxy and static proxy differences:

Static proxy: the.class file of the proxy class exists before the program runs.

Dynamic proxy: Use reflection to create proxy objects dynamically while the program is running

CGLIB and JDK dynamic proxy differences:

The Jdk must provide an interface to use it; CGLIB does not require a single non-abstract class to implement dynamic proxies

What are the isolation levels in Spring transactions?

Five constants representing the isolation level are defined in the TransactionDefinition interface:

TransactionDefinition. ISOLATION_DEFAULT: use a backend database default isolation level, Mysql default REPEATABLE_READ isolation level used Oracle READ_COMMITTED) isolation level used by default

TransactionDefinition. ISOLATION_READ_UNCOMMITTED: the lowest isolation level, allowing the read has not yet been submitted data changes, may lead to dirty reads, phantom read or not repeatable read.

TransactionDefinition. ISOLATION_READ_COMMITTED: allow read of concurrent transactions have to submit data, can prevent dirty reads, but phantom read or not repeatable read could still happen.

TransactionDefinition. ISOLATION_REPEATABLE_READ: many of the same field to read the results are consistent, unless the data have been modified by itself affairs on their own, can prevent the dirty read and not repeatable read, but phantom read could still happen.

TransactionDefinition. ISOLATION_SERIALIZABLE: the highest isolation level, completely obey the ACID isolation level. All transactions are executed one by one so that interference between transactions is completely impossible. That is, this level prevents dirty reads, unrepeatable reads, and phantom reads. But this severely affects the performance of the program. This level is also not typically used.

What kinds of transaction propagation behavior do Spring transactions have?

Cases that support the current transaction:

TransactionDefinition. PROPAGATION_REQUIRED: if a transaction exists, then join the transaction; If there is no transaction currently, a new transaction is created.

TransactionDefinition. PROPAGATION_SUPPORTS: if a transaction exists, then join the transaction; If there is no transaction currently, it continues in a non-transactional manner.

TransactionDefinition. PROPAGATION_MANDATORY: if a transaction exists, then join the transaction; If there is no transaction currently, an exception is thrown. (Mandatory: mandatory)

The current transaction is not supported:

TransactionDefinition. PROPAGATION_REQUIRES_NEW: create a new transaction, if a transaction exists, suspending the current transaction.

TransactionDefinition. PROPAGATION_NOT_SUPPORTED: run way of transaction, if a transaction exists, suspending the current transaction.

TransactionDefinition. PROPAGATION_NEVER: run way of transaction, if the current transaction, throw an exception. Other information:

TransactionDefinition. PROPAGATION_NESTED: if a transaction exists, then create a transaction for the current affairs of nested transactions to run; If no current affairs, the value of equivalent to the TransactionDefinition. PROPAGATION_REQUIRED.

Failure scenarios and usage considerations for @Transactional

Transactional @Transactional can be used on interfaces, classes, class methods, and declarative transactions:

For classes: When the @Transactional annotation is placed ona class, all public methods of that class are configured with the same transaction attribute information.

Apply to methods: When a class is configured with @Transactional and a method is configured with @Transactional, the method’s transactions override the Transactional configuration information of the class.

Use on interfaces: This is not recommended because the @Transactional annotation will fail once annotation is on an Interface and Spring AOP is configured to use CGLib dynamic proxies.

Transactional failure scenario:

The @Transactional application implements non-public methods: Spring implements AOP by default using dynamic proxies, which enhance target methods. Protected /private methods cannot be used to implement these methods, and Spring cannot dynamically implement Transactional logic.

Transactional method A calls method B of the same class (whether public or private), but method A does not declare an annotation transaction, whereas method B does. Method B’s transaction will not take effect after an external call to method A. This is also where mistakes are often made.

Error propagation of @transactional attribute

4. Database engine does not support transactions: Common MySQL databases use the innoDB engine that supports transactions by default. Once the database engine switches to myISAM, which does not support transactions, the transactions are essentially invalidated.

SpringBoot part

SpringBoot boot process

Springapplication. run encapsulates an instance of SpringApplication, and then executes the overloaded run method of that instance.

2. When SpringApplication encapsulates instances, Read all mTEA-INF/Spring.Factories in the CLASspath using the SPI mechanism XML configuration file ApplicationContextInitializer initializer (containers) and ApplicaiontListener (the listener), will both wrapped in SpringApplication instances

3, perform SpringApplication instance run method, run method the default initialization of an Annotation configuration containers AnnotationConfigApplicationContext, And load the applicationContext. The lister implementation creates the spring container, refreshContext (), implements the starter automation configuration, spring.Factories file loading, and bean instantiation.

4, perform the initial ApplicationContextInitializer above methods, and then loaded into the Bean container.

The principle of SpringBoot automatic configuration:

@enableAutoConfiguration Finds the meta-INF /spring.factories (with the beans you want to create) configuration file. Read the Spring.factories file in each starter

  1. SpringBoot launches load a large number of auto-configuration classes

  2. Let’s see if the functionality we need has an auto-configuration class written by SpringBoot by default;

  3. Let’s take a look at what components are configured in the auto-configuration class (as long as the component we want to use is available, we don’t need to configure it, if not, we may need to consider writing a configuration class for SpringBoot to scan).

  4. When you add a component to the auto-configuration class in the container, you get some properties from the Properties class. We can specify the values of these properties in the configuration file;

XxxxAutoConfigurartion: The auto-configuration class is used to add components to a container

XxxxProperties: is used to encapsulate related properties in the configuration file

Core annotations for Spring Boot

The core annotation is @SpringBootApplication and consists of three things

@springBootConfiguration: The @Configuration annotation is combined to realize the function of the Configuration file.

@enableAutoConfiguration: Enable the automatic configuration function.

@ComponentScan: Spring component scanning.

What are the common SpringBoot starter

Spring-boot-starter -web – Web and RESTful applications;

Spring-boot-starter-test – unit testing and integration testing;

Spring-boot-starter – JDBC – traditional JDBC;

Spring-boot-starter-security – Uses SpringSecurity for authentication and authorization

Spring-boot-starter-data-jpa – Spring data JPA with Hibernate;

Spring-boot-starter-data-rest – Uses Spring Data REST to publish simple REST services.

The core configuration file for Spring Boot

Application. Yml is generally used to define a single Application level, if used with spring-cloud-config.

2, bootstrap. yml (load first) System level parameters configuration, these parameters are generally unchanged.

For springMVC process:

1. User requests are sent to DispatcherServlet, which calls HandlerMapping processor mapper.

2. HandlerMapping finds the corresponding processor according to XML or annotations, generates the processor object and returns it to DispatcherServlet;

3. The DispatcherServlet calls the corresponding HandlerAdapter;

4. The HandlerAdapter calls the specific processor to handle the request through adaptation, and generates ModelAndView back to DispatcherServlet

5. DispatcherServlet sends ModelAndView to ViewReslover to parse the generated View and return it to DispatcherServlet;

6. DispatcherServlet renders View according to View;

->DispatcherServlet->HandlerMapping->Handler ->HandlerAdapter Handler ->ModelAndView ->DispatcherServlet->ModelAndView->ViewReslover->View ->DispatcherServlet-> Return to customer

Zookeeper + had + Springcloud part

Zuul is different from Gateway

1. Zuul is a Netflix project integrated into Spring-Cloud, while Gateway is a sub-project of Spring-Cloud.

2: Zuul does not provide asynchronous support, flow control is supported by Hystrix, gateway provides asynchronous support, provides abstract load balancing, provides abstract flow control; In theory, Gateway is better suited to improve system throughput (but not necessarily performance), which needs to be determined by rigorous pressure testing

3: The underlying implementation of both is servlet, but the Gateway nested a layer of WebFlux framework

4: Zuul can be used in other microservice frameworks without internal flow limiting and load balancing; Gateway can only be used in springcloud.

Analysis of Zuul principle

(1) : Requests to ZuulServlet (HttpServlet subclass) ZuulServlet has a zuulRunner object that initializes the RequestContext, which stores the requested data, RequestContext is shared by all ZuulFilters;

(2) : zuulRunner has the FilterProcessor (zuulFilter manager), which obtains zuulFilter from the FilterLoader;

(3) zuulservelet will execute a Pre-> Route -> POST filter and return the result to the client if there is an error in executing these filters.

Gateway Principle Analysis

(1) : The request arrives at the DispatcherHandler, which instantiates the HandlerMapping interface in the IOC container when it is initialized.

(2) : Use handlerMapping to match the corresponding Route according to the request URL, and then use the corresponding filter to forward the corresponding request and return the final response.

Working principles of Zookeeper (to be checked)

At the core of Zookeeper is atomic broadcasting, which ensures synchronization between servers. The protocol that implements this is called the Zab protocol. Zab protocol has two modes: recovery mode and broadcast mode.

Zoo is different from EUR

1. Zookeeper ensures CP (consistency) : Zoo registration service breaks down during election period and is unavailable during election period. Eureka guarantee AP (availability) : EUR all nodes are equal, as long as there is one can ensure service availability, and the queried data may not be the latest, which can well cope with the loss of some nodes caused by network failure

2. Zoo has the roles of leader and follower, and all nodes eur are equal.

3. Zoo adopts the 50% survival principle (to avoid brain splitting), WHILE EUR adopts the self-protection mechanism to solve the partition problem

Eur is essentially a project, zoo is just a process

ZooKeeper is based on CP and does not guarantee high availability. If ZooKeeper is selecting an owner or more than half of the machines in the ZooKeeper cluster are unavailable, data cannot be obtained. Eureka is ap-based and highly available, allowing access to locally cached data even when all machines are down. As a registry, the configuration does not change very often, only when a new version is released and the machine fails. CP is not appropriate for configurations that change infrequently, and aps can sacrifice consistency to ensure availability when they encounter problems, both by returning old data and caching data. So Eureka is ideally suited to be a registry. In a real world, most projects would probably use ZooKeeper because the cluster is not large enough and you rarely get to the point where more than half of the machines used as registries hang up. So it’s not really a big deal.

Hystrix principle (to be found) By maintaining a thread pool of its own. When the thread pool reaches the threshold, service degradation is initiated and fallback is returned to the default value. Why Hystrix fuse is needed to prevent avalanches, release resources in a timely manner, and prevent more cascading failures in the system? Prevent the failure of a single dependency from affecting the entire application;

Advantages and disadvantages of microservices 1. Each service is highly cohesive, loosely coupled and interface oriented;

2. Cost of inter-service communication, data consistency, increased difficulty of multi-service operation and maintenance, and THE efficiency of HTTP transmission is not as good as RPC

Eureka self-protection mechanism

1. Eur does not remove services that have not received a heartbeat for a long time and should expire

2, still accept new service registration and query requests, but will not be synchronized to other nodes (high availability)

3. When the network is stable, the new registration information of the current instance will be synchronized to other nodes (final consistency).

Mybatis part

What is Mybatis? Mybatis is a semi-ORM (Object relational Mapping) framework, which encapsulates JDBC internally. When developing, you only need to pay attention to THE SQL statement itself, and do not need to spend energy to deal with the complex process of loading drivers, creating connections, creating statements and so on. Programmers directly write the original SQL, SQL execution can be strictly controlled, high flexibility. MyBatis can configure and map native information using XML or annotations to map POJOs to records in the database, eliminating almost all of the JDBC code and manual setting of parameters and fetching result sets. The statements to be executed are configured through XML files or annotations, and the SQL statements to be executed are generated by mapping Java objects to the dynamic parameters of the SQL in the statement. Finally, the MYBatis framework executes the SQL and maps the results to Java objects and returns them. (The process from executing SQL to returning result).

The advantages of Mybaits

1, based on SQL statement programming, quite flexible, will not cause any impact on the existing design of the application program or database, SQL written in XML, remove the COUPLING of SQL and program code, easy to unified management; Provides XML tags that support writing dynamic SQL statements and can be reused.

2, compared with JDBC, reduce more than 50% of the code, eliminate a lot of JDBC redundant code, do not need to manually switch the connection; Good compatibility with various databases (because MyBatis uses JDBC to connect to the database, so as long as JDBC support database MyBatis support).

3. Good integration with Spring;

4. Provide mapping labels to support ORM field relational mapping between objects and databases; Provides object-relational mapping labels to support object-relational component maintenance.

Disadvantages of MyBatis framework

1, SQL statement writing workload is large, especially when the field, associated table, for developers to write SQL statement skills have certain requirements.

2, SQL statements rely on the database, resulting in poor database portability, can not be replaced at will database.

MyBatis framework for applications

MyBatis focuses on SQL itself and is a flexible DAO layer solution.

2. MyBatis will be a good choice for projects with high performance requirements or more variable requirements, such as Internet projects.

What are the differences between MyBatis and Hibernate?

1. Unlike Hibernate, Mybatis is not a complete ORM framework because Mybatis requires programmers to write their own Sql statements

2, Mybatis directly write original SQL, can strictly control SQL performance, high flexibility, very suitable for the software development of relational data model requirements are not high, because this kind of software needs to change frequently, but a change requires rapid output results. However, the premise of flexibility is that Mybatis cannot achieve database independence. If you need to implement software supporting a variety of databases, you need to customize multiple sets of SQL mapping files, and the workload is heavy.

Hibernate object/relational mapping ability, database independence is good, for software with high requirements of relational model, if Hibernate development can save a lot of code, improve efficiency.

What is the difference between #{} and ${}?

${} is a string substitution.

2, Mybatis will replace #{} with? Call the set method in PreparedStatement to assign the value.

3, Mybatis in the process, is to {}, is to replace {} into the value of the variable.

4, using #{} can effectively prevent SQL injection, improve system security.

What if the attribute name in the entity class is different from the field name in the table?

The first is to make the alias of the field name consistent with the attribute name of the entity class by defining the alias of the field name in the SQL statement of the query

<select ID = “selectOrder” parameterType = “int” resulteType = “me.gacl.domain.order” > select order_id ID, order_no orderno ,order_price price form orders where order_id=#{id};

The second is to map the one-to-one correspondence between field names and entity class attribute names.

<! — Map primary key field with id attribute — >

<! – Use the result attribute to map non-primary key fields, property is the name of the entity class attribute, column is the attribute in the data table.

How to write fuzzy query like statement?

Type 1: Add SQL wildcards to Java code.

Smi string wildcardname = “% %”;

list names = mapper.selectlike(wildcardname); select * from foo where bar like #{value}

2. Concatenate wildcards in SQL statements, which causes SQL injection

String wildcardname = “smi”;

list names = mapper.selectlike(wildcardname); select * from foo where bar like “%”#{value}”%”

How does the Mapper interface work? Can methods in Mapper interface be overloaded with different parameters?

Dao interfaces are Mapper interfaces. The full name of the interface is the value of namespace in the mapping file. The method name of the interface is the ID of the Statement of the Mapper in the mapping file. The parameters in the interface method are the parameters passed to SQL.

The Mapper interface has no implementation class. When an interface method is called, the interface name + method name concatenation string is used as the key value to uniquely locate a MapperStatement. In Mybatis, each,, and tag is parsed into a MapperStatement object. For example: Com. Mybatis3. Mappers. StudentDao. FindStudentById, Can only find the namespace for the com. Mybatis3. Mappers. StudentDao id for findStudentById MapperStatement below. Methods in the Mapper interface cannot be overridden because they use the save and find strategy of the full name + method name. Mapper interface works by JDK dynamic proxy. Mybatis will use JDK dynamic proxy to generate a proxy object for Mapper interface. The proxy object will intercept the interface method and execute the SQL represented by MapperStatement. The SQL execution results are then returned. How does Mybatis paginate? How does paging plug-ins work? Mybatis uses the RowBounds object for paging, which is memory paging performed against a ResultSet ResultSet rather than physical paging. Physical paging can be done by writing parameters with physical paging directly in SQL, or physical paging can be done using paging plug-ins. The basic principle of the paging plug-in is to use the plug-in interface provided by Mybatis to implement a custom plug-in to intercept the SQL to be executed in the interception method of the plug-in, and then rewrite the SQL to add the corresponding physical paging statement and physical paging parameters according to the dialect. How does Mybatis encapsulate SQL execution results as target objects and return them? What are the mappings? The first is to use tags to define the mapping between database column names and object attribute names one by one. The second is to use the SQL column alias function to write the column alias as the object property name. Mybatis creates objects by reflection after mapping between column names and attribute names. At the same time, Mybatis uses reflection to assign values to the attributes of the object one by one and returns them. The assignment cannot be completed for those attributes that cannot find the mapping relationship. How do I perform batch inserts? First, create a simple INSERT statement: INSERT into names (name) values (#{value}) then perform a batch insert in Java code like this: list < string > names = new arraylist(); Names. The add (” Fred “); Names. The add (” barney “); Names. The add (” Betty “); Names. The add (” Wilma “); / / note here executortype. Batch sqlsession sqlsession = sqlsessionfactory. Opensession (executortype. Batch); try { namemapper mapper = sqlsession.getmapper(namemapper.class); for (string name: names) { mapper.insertname(name); } sqlsession.commit(); } catch (Exception e) { e.printStackTrace(); sqlSession.rollback(); } finally { sqlsession.close(); } How do I get the automatically generated (primary) key value? The insert method always returns an int that represents the number of rows inserted. With a self-growth strategy, automatically generated key values can be set to the parameter object passed in after the INSERT method. Insert into names (name) values (#{name}) name name = new name(); Name. Elegantly-named setname (” Fred “); int rows = mapper.insertname(name); // When done, the ID has been set to the object system.out.println(” rows = “+ rows); System.out. println(” generated key value = “+ name.getid()); How do I pass multiple parameters in Mapper? Public UserselectUser(String name,String area); In the corresponding XML,#{0} represents the first parameter in the DAO layer,#{1} represents the second parameter in the DAO layer, and more parameters can be added later. <select id=”selectUser”resultMap=”BaseResultMap”> select * fromuser_user_t where user_name = #{0} and user_area=#{1}

2. Use @param annotations:

Public interface usermapper {user selectUser (@param(” username “) string username,@param(” hashedPassword “) string hashedpassword); } It can then be used in XML as follows (it is recommended to encapsulate as a map and pass as a single parameter to mapper) select ID, username, hashedpassword from some_table where username = #{username} and hashedpassword = #{hashedpassword}

3. Third: Encapsulate multiple parameters into a Map

try {

// Map file namespace. Since we have more than two parameters and only one Object parameter collection in the method, we use the Map collection to load our parameters

Map < String, Object > map = new HashMap();

map.put(“start”, start);

map.put(“end”, end);

return sqlSession.selectList(“StudentID.pagination”, map);

}catch (Exception e) {

e.printStackTrace();

sqlSession.rollback();

throw e;

} finally {

MybatisUtil.closeSqlSession();

}

What is Mybatis dynamic SQL? How does it work? What dynamic SQL is there?

Mybatis dynamic SQL can be written in Xml mapping file in the form of tag dynamic SQL, execution principle is based on the value of the expression to complete the logical judgment and dynamic splicing SQL function.

Mybatis provides nine dynamic SQL tags: trim | where | set | foreach | if | choose | s | otherwise | bind.

Xml mapping file, in addition to the common select | insert | updae | delete tags, what other tags?

、、、、, plus 9 tags of dynamic SQL, including SQL fragment tags, which import SQL fragments through tags and generate policy labels for primary keys that do not support self-increment.

In the Xml mapping files of Mybatis, can the IDS of different Xml mapping files be repeated?

Different Xml mapping files, if configured with namespace, then the ID can be repeated; If no namespace is configured, the ID must be unique.

Namespace + ID is used as the key of Map<String, MapperStatement>. If there is no namespace, only ids are left. Duplicate ids will overwrite each other. With a namespace, the natural ID can be repeated. With different namespaces, the namespace+ ID will naturally be different.

Mybatis semi-automatic ORM mapping tool What’s the difference between it and automatic?

Hibernate is a fully automated ORM mapping tool. When using Hibernate to query associated objects or associated collection objects, it can be directly retrieved based on the object relational model, so it is fully automated. While Mybatis needs to write SQL manually when querying associated objects or associated collection objects, so it is called semi-automatic ORM mapping tool. One to one, one to many associative query?

select * from class c,teacher t where c.teacher_id=t.t_id and c.c_id=#{id}

How many ways can MyBatis implement one-to-one? How does it work?

There are joint query and nested query. The joint query is a joint query of several tables, which can be queried only once. You can configure one-to-one classes by configuring the Association node in the resultMap.

In a nested query, you can first query a table, and then query data in another table based on the foreign key ID of the result in the table, again using association configuration, but the query in the other table using select attribute configuration.

Does Mybatis support lazy loading? If so, how does it work?

Mybatis only supports delayed loading of association associative objects and collection associative objects. Association refers to one-to-one query and collection refers to one-to-many query. In Mybatis configuration file, you can configure whether to enable lazy-loading lazyLoadingEnabled = true | false.

The principle is that CGLIB is used to create a proxy object for the target object. When the target method is called, the interceptor method is entered, such as a.geb ().getName(). The interceptor invoke() method finds that A.geb () is null. A. setb (); a.getName (); a.getname (); a.getb (); a.getname (); This is the basic principle of lazy loading. Of course, not only Mybatis, almost all including Hibernate, support lazy loading principle is the same.

Mybatis level 1, level 2 cache

1. Level 1 Cache: A HashMap local Cache based on PerpetualCache, which is stored at Session scope. When a Session is flushed or closed, all caches in that Session are cleared, enabling Level 1 Cache by default.

Level 2 caches are PerpetualCache and HashMap by default. The difference is that the Mapper storage scope is PerpetualCache and you can customize the storage source, such as Ehcache. Level 2 caching is not enabled by default. To enable level 2 caching, using the Level 2 cache attribute class requires implementing the Serializable interface (which can be used to store the state of an object), which can be configured in its mapping file.

If C/U/D has been applied to one of these domains (Session level 1 / Namespaces level 2), caches will be cleared by default.

What is interface binding for MyBatis? What are the implementation methods?

Interface binding is to define any interface in MyBatis and bind the methods in the interface to SQL statements. We can call interface methods directly, so that we can have more flexible choices and Settings compared with the methods provided by SqlSession.

Interface binding can be implemented in two ways. One is through annotation binding, which is to add @SELECT, @update and other annotations to the interface methods, which contain Sql statements to bind.

The other option is to bind by writing SQL in XML. In this case, to specify the namespace in the XML mapping file must be the full path name of the interface. When Sql statements are simple, annotations are used for binding. When Sql statements are complex, XML is used for binding. XML is often used for binding.

What are the requirements when using MyBatis mapper interface?

Mapper interface method name is the same as the ID of each SQL defined in mapper.xml.

The input parameter types of Mapper interface methods are the same as those of parameterType for each SQL defined in mapper.xml.

3. The output parameter type of the Mapper interface method is the same as the resultType type of each SQL defined in mapper.xml;

4. Namespace in mapper. XML file is the classpath of Mapper interface.

Describe the operation principle of Mybatis plug-in, and how to write a plug-in

A: Only ParameterHandler, ResultSetHandler, StatementHandler, and Executor interfaces can be used as plugins in Mybatis. The interface method interception function is implemented by generating proxy objects for the interface to be intercepted. Each of the four methods of the interface object is invoked, specifically the Invoke () method of InvocationHandler, which, of course, only intercepts those methods that you specify to be intercepted.

Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor