In the basic knowledge of mybatis, we can already see the working mode of mybatis (see: "MyBatis——-Basic Knowledge"). But why should you learn how mybatis works? Because, with the continuous development of the mybatis framework, it has become more and more automated. From code generation to basic use, we can complete all CRUD operations of a simple application without even writing a SQL. From native mybatis to mybatis-spring, to mybatis-plus to mybatis-plus-spring-boot-starter. Spring is developing, and mybatis is also developing.
万变的外观 will eventually confuse people's eyes, as long as we grasp the core we will never be confused!
Working principle prototype map
Use the most intuitive map to conquer your heart!
Working principle analysis
mybatis application builds SqlSessionFactory (SqlSessionFactory is thread-safe) from SqlSessionFactoryBuilder from mybatis-config.xml configuration file (you can also use Java file configuration, need to add @Configuration) ;
Then, the instance of SqlSessionFactory directly opens a SqlSession, then obtains the Mapper object through the SqlSession instance and runs the SQL statement of the Mapper mapping, completes the CRUD and transaction commit to the database, and then closes the SqlSession.
说明: SqlSession is a single-threaded object, because it is non-thread-safe, is the exclusive object of the persistence operation, similar to the Connection in jdbc, the bottom layer encapsulates the jdbc connection.
Detailed process is as follows:
1, load mybatis global configuration file (data source, mapper mapping file, etc.), parse configuration file, MyBatis generates Configuration based on XML configuration file, and one MappedStatement (including parameter mapping) Configuration, dynamic SQL statement, result mapping configuration), which corresponds to the <select | update | delete | insert> tag item. 2, SqlSessionFactoryBuilder generates a SqlSessionFactory through the Configuration object, used to open SqlSession. 3, SqlSession object completion and database interaction: a, the user program calls the mybatis interface layer api (that is, the method in the Mapper interface) b, SqlSession finds the corresponding MappedStatement object by calling the IAL's Statement ID c. Through the Executor (responsible for the generation of dynamic SQL and the maintenance of the query cache), the MappedStatement object is parsed, the sql parameter is transformed, the dynamic sql is spliced, and the jdbc Statement object is generated. d, JDBC executes sql.
e, with the result mapping relationship in MappedStatement, the returned result is converted into a HashMap, JavaBean and other storage structures and returned.
mybatis level map: