In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what is the overall structure and operation process of Mybatis". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
What is Mybatis?
Mybatis is a persistence layer framework for data persistence. The main manifestation is to map SQL to POJO and decouple SQL from the code. The basic concepts are shown in the figure:
When in use, take User as an example, UserMapper defines the findById interface, which returns a User object, and the implementation of the interface is an xml configuration file. The xml file defines the SQL required for the implementation in the corresponding interface. In order to achieve the goal of decoupling SQL from code.
Select user_id id,user_name userName,user_age age from t_user where user_id=# {id} MyBatis, an open source Java project from Apache, is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. Mybatis can configure Sql statements in the XML file to avoid hard-coding Sql statements in the Java class. Characteristics
Through parameter mapping, 1.Mybatis can flexibly configure parameters in the configuration file in SQL statements, avoiding configuring parameters (JDBC) in Java classes.
Through the output mapping mechanism, 2.Mybatis automatically maps the retrieval of the result set to the corresponding Java object to avoid manual retrieval (JDBC) of the result set.
3.Mybatis can manage database connections through Xml configuration files
Introduction to core classes
1.SqlSessionaFactoryBuilder: this class is mainly used to create a SqlSessionFactory, which can be instantiated, used, and discarded, but once a SqlSessionFactory is created, it is no longer needed. Therefore, the best scope of an SqlSessionFactoryBuilder instance is the method scope (that is, local method variables).
2.SqlSessionFactory: the role of this class to create SqlSession, we can also see from the name, this class uses the factory pattern, every time the application accesses the database, we have to create SqlSession through SqlSessionFactory, so the life cycle of SqlSessionFactory and the entire Mybatis is the same. This also tells us that we cannot create multiple SqlSessionFactory of the same data. If we create more than one, it will consume the connection resources of the database and cause the server to tamp. Singleton mode should be used. Avoid excessive connection consumption and make it easy to manage.
3.SqlSession: SqlSession is equivalent to a session. Every time you visit the database, you need such a session. You may think of Connection in JDBC. It is similar, but there are differences, not to mention that almost all connections use connection pooling technology, which is returned directly after use and not destroyed like Session. Note: it is a thread-unsafe object. We need to be very careful when designing multithreading. We need to pay attention to its isolation level, database locks and other advanced features when operating the database. In addition, every SqlSession created must be closed in time. Its long-term existence will reduce the active resources of the database connection pool and have a great impact on system performance. We usually close it in the finally block. In addition, SqlSession lives in the requests and operations of an application, and can execute multiple Sql to ensure the consistency of transactions. During the execution of SqlSession, there are several major objects:
3.1.Executor: an executor that dispatches StatementHandler, ParameterHandler, ResultSetHandler, and so on to execute the corresponding SQL. Among them, StatementHandler is the most important. 3.2.StatementHandler: the function is to use the Statement (PreparedStatement) of the database to perform operations. It is the core of the four major objects and acts as a connecting link between the preceding and the next. Many important plug-ins are implemented by intercepting it. 3.3.ParamentHandler: used to handle the SQL parameter. 3.4.ResultSetHandler: for encapsulation and return processing of the dataset.
4.Mapper: mappers are interfaces that you create and bind statements you map. The instance of the mapper interface is obtained from SqlSession, and its function is to send SQL and return the result we need. Or execute SQL to change the data in the database, so it should be within the transactional method of SqlSession, and in Bean managed by Spring, Mapper is a singleton.
Functional architecture: we divide the functional architecture of Mybatis into three layers
(1) API interface layer: provides external use of the interface API, developers through these local API to manipulate the database. As soon as the interface layer receives the call request, it will call the data processing layer to complete the specific data processing.
(2) data processing layer: responsible for specific SQL lookup, SQL parsing, SQL execution and result mapping processing. Its main purpose is to complete a database operation according to the called request.
(3) basic support layer: responsible for the most basic functional support, including connection management, transaction management, configuration loading and cache processing, these are common things, extracted as the most basic components. It provides the most basic support for the upper data processing layer.
Frame structure:
(1) load configuration: the configuration comes from two places, one is the configuration file, and the other is the comments of Java code. The configuration information of SQL is loaded into MappedStatement objects (including incoming parameter mapping configuration, executed SQL statement, result mapping configuration) and stored in memory.
(2) SQL parsing: when the API interface layer receives the call request, it will receive the ID and the incoming object (which can be Map, JavaBean or basic data type) of the incoming SQL. The Mybatis will find the corresponding MappedStatement according to the ID of the SQL, and then parse the MappedStatement according to the passed parameter object. After parsing, you can get the final SQL statement and parameters to be executed.
(3) SQL execution: take the final SQL and parameters to the database for execution, and get the results of operating the database.
(4) result mapping: convert the results of operating the database according to the mapped configuration, which can be converted to HashMap, JavaBean or basic data types, and return the final result.
Perform the process:
1. Get SqlsessionFactory: initialize the configuration object based on the configuration file (global, sql mapping)
two。 Get sqlSession: create a DefaultSqlSession object containing Configuration and Executor (create a corresponding Executor based on defaultExecutorType in the global configuration file)
3. Get the interface proxy object MapperProxy:DefaultSqlSession.getMapper and get the MapperProxy corresponding to the Mapper interface
4. Perform additions, deletions, alterations and searches
1. Call DefaultSqlSession to add, delete, modify and check 2, create StatementHandler (create ParameterHandler,ResultSetHandler at the same time) 3, call StatementHandler precompilation parameters and set parameter values, use ParameterHandler to set parameters 4 for sql, call StatementHandler to add, delete, modify and check 5, ResultSetHandler encapsulate the results
Similarities and differences with Hibernate
There must be a reason why Mybatis is becoming more and more popular. Take a brief look at its similarities and differences with Hibernate, which is also a persistence layer framework.
Mapping mode
From the simple concepts above, we can see that Mybatis actually focuses on the mapping between POJO and SQL. On the other hand, Hibernate is mainly the object-relational mapping between POJO and database tables. The former has less control and relatively more code, while the latter is less flexible and more automated, and belongs to the same type as Eloquent in PHP.
Performance
Mybatis is based on native JDBC, which has better performance than Hibernate with secondary encapsulation of JDBC.
Development and maintenance
After configuring the entity class, Hibernate is relatively simple and comfortable to use, but the early learning curve is relatively steep, and later tuning is more troublesome. Mybatis controls the particles of SQL a little bit finer, and looks shabby by comparison. Because of the direct mapping of SQL, mobility is a problem. Mybatis novice on the road
Introduction to MyBatis
Mybatis, an open source Java project of Apache, is a persistence layer framework that supports dynamic Sql statements. Mybatis can configure Sql statements in the XML file to avoid hard-coding Sql statements in the Java class. Compared to JDBC:
Through parameter mapping, Mybatis can flexibly configure parameters in the configuration file in SQL statements, avoiding configuring parameters (JDBC) in Java classes.
Through the output mapping mechanism, Mybatis automatically maps the retrieval of the result set to the corresponding Java object to avoid manual retrieval (JDBC) of the result set.
Mybatis can manage database connections through Xml configuration files.
The overall structure and running process of MyBatis
The overall construction of Mybatis consists of a data source configuration file, an Sql mapping file, a session factory, a session, an executor, and an underlying encapsulation object.
1. Data source profile
Through the way of configuration, the configuration information of the database is independent from the application, and is managed and configured by independent modules. The data source configuration file of Mybatis includes database driver, database connection address, user name and password, transaction management, etc., and you can also configure the number of connections and idle time of the connection pool.
The basic configuration information of a SqlMapConfig.xml is as follows:
2.Sql mapping file
All database operations in Mybatis are based on the mapping file and the configured sql statement, in which any type of sql statement can be configured. The framework completes the mapping configuration of sql statements and input and output parameters according to the parameter configuration in the configuration file.
The Mapper.xml configuration file is roughly as follows:
3. Conversation Factory and conversation
The session factory SqlSessionFactory class in Mybatis can load the resource file and read the data source configuration SqlMapConfig.xml information, thus generating a session instance SqlSession that can interact with the database. The session instance SqlSession operates on the database according to the sql configured in the Mapper.xml file.
4. Running process
The session factory SqlSessionFactory gets the SqlMapConfig.xml configuration file information by loading the resource file, and then generates a session instance SqlSession that can interact with the database.
The session instance can add, delete, modify and query according to the Sql configuration in the Mapper configuration file.
Within the SqlSession session instance, the database is operated through the executor Executor, and Executor relies on the encapsulated object Mappered Statement, which installs the information read from the mapper.xml file (sql statements, parameters, result set types).
Mybatis interacts with database through the combination of executor and Mappered Statement.
Execution flowchart:
Test engineering construction
New maven project
two。 Add dependency pom.xml
4.0.0com.slmybatiscopyright demo0.0.1 on SNAPSHOT4.123.4.15.1.321.2.17 junitjunit$ {junit.version} org.mybatismybatis$ {mybatis.version} mysqlmysql-connector-java$ {mysql.version} log4jlog4j$ {log4j.version}
3. Write a data source configuration file SqlMapConfig.xml
4. Write SQL mapping configuration file productMapper.xml
5. Write test code TestClient.java
/ / use productMapper.xml configuration file public class TestClient {/ / define session SqlSession SqlSession session = null; @ Before public void init () throws IOException {/ / define mabatis global configuration file String resource = "SqlMapConfig.xml"; / / load mybatis global configuration file / / InputStream inputStream = TestClient.class.getClassLoader (). GetResourceAsStream (resource); InputStream inputStream = Resources.getResourceAsStream (resource); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder (); SqlSessionFactory factory = builder.build (inputStream) / / generate session sqlsession session = factory.openSession () according to sqlSessionFactory;} / / query all data of all user tables @ Test public void testSelectAllUser () {String statement = "com.sl.mapper.ProductMapper.selectAllProduct"; ListlistProduct = session.selectList (statement); for (Product product:listProduct) {System.out.println (product);} / close session session.close () }} public class Product {private int Id; private String Name; private String Description; private BigDecimal UnitPrice; private String ImageUrl; private Boolean IsNew; public int getId () {return Id;} public void setId (int id) {this.Id = id;} public String getName () {return Name;} public void setName (String name) {this.Name = name;} public String getDescription () {return Description;} public void setDescription (String description) {this.Description = description } public BigDecimal getUnitPrice () {return UnitPrice;} public void setUnitPrice (BigDecimal unitprice) {this.UnitPrice = unitprice;} public String getImageUrl () {return Name;} public void setImageUrl (String imageurl) {this.ImageUrl = imageurl;} public boolean getIsNew () {return IsNew;} public void setIsNew (boolean isnew) {this.IsNew = isnew @ Override public String toString () {return "Product [id=" + Id + ", Name=" + Name + ", Description=" + Description + ", UnitPrice=" + UnitPrice + ", ImageUrl=" + ImageUrl + ", IsNew=" + IsNew+ "]";}} 6. This is the end of running the test case "what is the overall architecture and running process of Mybatis". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.