(Java Daily Talk: Day 19 - Employment Interview Knowledge Clearance Strategy) MyBatis

JPA principle

Transaction: Transaction is an indispensable component model in computer applications, which guarantees the atomicity, consistency, isolation and durability of user operations.

Local transactions: Closely dependent on the underlying resource manager, transaction processing is limited to the current transaction resources. This transaction processing method does not depend on the application server, so it is flexible to deploy but cannot support distributed transactions of multiple data sources.

Distributed transaction: Java Transaction Programming Interface (JTA: Java Transaction API) and Java Transaction Service (JTS: Java Transaction Service) provide distributed transaction services for the J2EE platform. Distributed transaction (Distributed Transaction) includes transaction manager (Transaction Manager) and one or more resource managers (Resource Manager) supporting XA protocol. We can regard the resource manager as any type of persistent data storage; the transaction manager is responsible for the coordination and control of all transaction participating units.

MyBatis cache

There are first-level cache and second-level cache in MyBatis, and the first-level cache is enabled by default. The first-level cache refers to the cache at the SqlSession level. When the same SQL statement is queried in the same SqlSession, the query after the second time will not be queried from the database, but directly obtained from the cache. The first-level cache can cache up to 1024 SQL. The second-level cache refers to the cache that can cross SqlSession. It is a cache at the mapper level. Different sqlSessions can share the cache at the mapper level.

Level 1 cache: HahsMap local cache based on PerpetualCache. Its storage scope is Session. When the Session is flushed or closed, all caches will be cleared. Level 1 cache is enabled by default.

The mechanism of the second-level cache is the same as that of the first-level cache. The default is to use PerpetualCache and HahsMap storage. The difference is that its storage scope is Mapper (Namespace), and the storage source can be customized, such as Ehcache. The second-level cache is not enabled by default. To use the second-level cache attribute class, you need to implement the Serializeable serialization interface (which can be used to save the state of the object), which can be configured in its mapping file.

For the cache data update mechanism, when a scope (first-level cache Session/level-two cache Namespaces) performs C/U/D operations, the cache in the select under the scope will be cleared by default.

What is MyBatis?

MyBatis is an excellent persistence layer framework, a semi-ORM (object-relational mapping) framework, which supports customized SQL, stored procedures and advanced mapping. MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets. MyBatis can use simple XML or annotations to configure and map native types, interfaces, and Java POJOs as records in the database.

What is ORM?

ORM, object-relational mapping, is a technology to solve the mapping relationship between relational database data and simple Java objects (POJO). Simply put, ORM is described by using hard-core metadata between objects and databases. Automatically persist the objects in the program to the relational database.

Why is MyBatis a semi-automatic ORM mapping tool? What is the difference between it and fully automatic?

Hibernate is a fully automatic ORM mapping tool. When using Hibernate to query associated objects or associated collection objects, it can be directly obtained according to the object relationship model, so it is fully automatic.

When Mybatis queries associated objects or associated collection objects, it needs to manually write sql to complete, so it is called a semi-automatic ORM mapping tool.

Does MyBatis support lazy loading? If supported, how is it implemented?

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

Its principle is to use CGLIB to create the proxy object of the target object. When the target method is called, enter the interceptor method, such as calling a.getB().getName(), and the interceptor invoke() method finds that a.getB() is If the value is null, then it will send the pre-saved sql query associated with the B object separately, query B, and then call a.setB(b), so the object b attribute of a has a value, and then complete a.getB( ).getName() method call. This is the basic principle of lazy loading.

Problems in traditional JDBC development? How does MyBatis solve these problems?

1. Frequent creation and release of database connection objects will easily cause waste of system resources and affect system performance. This problem can be solved by using a connection pool. But using jdbc requires you to implement the connection pool yourself.

Solution: configure the data connection pool in mybatis-config.xml, and use the connection pool to manage database connections

2. There are hard-coded sql statement definitions, parameter settings, and result set processing. In the actual project, the sql statement is more likely to change. Once there is a change, the java code needs to be modified, and the system needs to be recompiled and republished. Not easy to maintain.

Solution: Separate the Sql statement from the Java code in the XXXmapper.xml file

3. There is hard coding in using prepareStatement to pass parameters to the occupancy symbol, because the where conditions of the sql statement are not necessarily, there may be more or less, and the code needs to be modified to modify the sql, and the system is not easy to maintain.

Solution: Mybatis automatically maps java objects to sql statements

4. There are duplicate codes in the result set processing, which makes the processing troublesome. It would be more convenient if it can be mapped to a Java object.

Solution: Mybatis automatically maps sql execution results to java objects

Advantages and disadvantages of Mybatis

advantage

Compared with traditional database access technologies, ORM has the following advantages:

Based on SQL statement programming, it is quite flexible and will not have any impact on the existing design of the application program or database. SQL is written in XML, which decouples sql from the program code and facilitates unified management; XML tags are provided to support the writing of dynamic SQL statements , and reusable

Compared with JDBC, it reduces the amount of code by more than 50%, eliminates a large number of redundant codes of JDBC, and does not require manual switch connection

Very good compatibility with various databases (because MyBatis uses JDBC to connect to the database, all databases Mybatis supports as long as JDBC is supported)

difference

Can be well integrated with Spring

shortcoming

The workload of writing SQL statements is very heavy, especially when there are many fields and many associated tables, there are certain requirements for developers to write SQL statements

SQL statements depend on the database, resulting in poor database portability, and the database cannot be replaced at will

What are the MyBatis programming steps?

1. Create SqlSessionFactory

2. Create SqlSession through SqlSessionFactory

3. Perform database operations through SqlSession

4. Call session.commit() to commit the transaction

5. Call session.close() to close the session

What is the functional architecture of myBatis?

We divide the functional architecture of Mybatis into three layers:

API interface layer: the interface API provided for external use, and developers use these local APIs to manipulate the database. Once the interface layer receives the call request, it will call the data processing layer to complete the specific data processing.

Data processing layer: responsible for specific SQL lookup, SQL parsing, SQL execution and execution result mapping processing, etc. Its main purpose is to complete a database operation according to the call request.

Basic support layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading, and cache processing. These are common things, and they are extracted as the most basic components. Provide the most basic support for the upper data processing layer.

The life cycle of Spring Bean

The life cycle of Spring Bean is simple and easy to understand. When a bean instance is initialized, it needs to perform a series of initialization operations to achieve a usable state. Similarly, when a bean is no longer called, it needs to be destructed and removed from the bean container.

The Spring bean factory is responsible for managing the life cycle of beans created in the spring container.

Callback method called after initialization.

Callback method called before destruction.

The Spring framework provides the following four ways to manage bean lifecycle events:

InitializingBean and DisposableBean callback interface

Additional Aware Interfaces for Special Behaviors

Custom init() method and destroy() method in Bean configuration file

@PostConstruct and @PreDestory annotation methods

Spring MVC running process

1. spring mvc submits all requests to DispatcherServlet, and he will entrust other modules of the application system to be responsible for the real processing of requests

2. DispatcherServlet queries one or more HandlerMappings to find the Controller that handles the request

3. DispatcherServlet submits the request to the target Controller

4. After the Controller performs business logic processing, it will return a ModelAndView

5. Dispatcher queries one or more ViewResolver view resolvers and finds the view object specified by the ModelAndView object

6. The attempt object is responsible for rendering and returning to the client

What design patterns are used in the Spring framework?

Proxy mode - used more in AOP and remoting

Singleton mode - beans defined in the Spring configuration file default to singleton mode

Template method - used to solve the problem of code duplication

Front controller - Spring provides DispatcherServlet to distribute requests

Try to help (View Helper)-spring provides a series of JSP tags, high-efficiency macros to help integrate scattered code into the view

Dependency injection - the core idea throughout the BeanFactory/ApplicationContext interface

Factory mode - BeanFactory is used to create instances of objects

How does message middleware ensure message consistency?

1. The active application first sends the message to the message middleware, and the message status is marked as pending

2. After the message middleware receives the message, it persists the message to the message storage, but does not deliver the message to the passive application

3. The message middleware returns the message persistence result (successful or invalid), and the active application judges how to handle business operations based on the returned result;

        1. Failure: Abandon the business operation processing and end (the failure result must be returned to the upper layer)

        2. Success: Execute business operation processing

4. After the business operation is completed, send the business operation result (success/failure) to the message middleware

5. After the message middleware receives the business operation result, it processes it according to the result

        1. Failure: delete the message in the message storage, end

        2. Success: update the status of the message in the message storage to be sent (can be sent), and then perform message delivery

6. After the previous forward process is successful, deliver a message to the passive application

Guess you like

Origin blog.csdn.net/weixin_50249953/article/details/124955706