In the first article, we simply wrote and ran a general process of querying a certain data in the database. Now let's study the operation process of MyBatis. How does it run?
Operation process
1. Detailed flow of code in test class
We all know that the entry of a program in Java is the main function, and here is no exception. So let's first look at the main function, which is written in our Test class. The code is as follows:
package com.rjxy.mybatis.shiyan1; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.rjxy.mybatis.shiyan1.User; public class UserTest { public static void main(String[] args) throws IOException{ // TODO Auto-generated method stub String resource = "config.xml"; //Load the configuration file for mybatis (it also loads the associated mapping file) Reader reader = Resources.getResourceAsReader(resource); //Build a factory for sqlSession SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); //Create an sqlSession that can execute sql in the mapping file SqlSession session = sessionFactory.openSession(); //Identity string of mapping sql String statement = "com.rjxy.mybatis.shiyan1.userMapper.getUser"; //Execute the query and return the sql of a unique user object User user = session.selectOne(statement, 1); System.out.println(user); } }
Step 1:
We found that in the main function, we first put config.xml into a string variable. We know that the config.xml configuration file is the location for storing database information and Mapper files.
Step 2:
Resources is used to load the configured configuration file. Resources is the class under the ibatis.io package, that is, an IO stream, which is used to read and write files. The xml file is loaded in through getResourceAsStream and the configuration file is parsed into a stream. Stored in a reader object, we need to know that the reader class is Java Base class for all readers in io. It doesn't matter if you don't understand it here. It can be understood that the configuration file information is parsed and put into the reader object.
Step 3:
Do we see a SqlSessionFactoryBuilder object? It is the builder of SqlSessionFactory. We called his build() method.
Let's look at the source code of the build method:
We found that there is an XMLconfigBuilder object in it. It is a builder used to parse XML files. It parses mybatis configuration files through its parse() method
Then we found that after parse() parsing, it returned a configuration object, which is used to store the results of mybatis core configuration file parsing. Who did the configuration return to? Continue to look at the source code:
It also returns a build method, passes the just returned value configuration as a parameter into this method, and returns a DefaultSqlSessionFactory object, which is the implementation class of SqlSessionFactory, which is used to produce the defaultSqlSession object. In this way, the third step above is really over..
It doesn't matter if you don't understand the above. Let's first learn the overall process and know that the SqlSessionFactoryBuilder object new is used to build SqlSessionFactory.
Step 4:
We generate sqlsessions that can execute sql in the mapping file through the openSession() method under sessionFactory.
Step 5:
The sql statement under the mapper file we are going to execute, so how do we determine which sql statement under which mapper file? Looking back at the first step, we introduced the config.xml file. For all mapper files specified in this file, we only need to find the sql statement to be executed based on the namespace attribute of mapper in a file and the id in select. Therefore, we splice the namespace and id to be searched into a string as parameters in the seleceOne method to find the corresponding sql statement.
<mapper namespace="com.rjxy.mybatis.shiyan1.userMapper"> <select id="getUser" parameterType="int" resultType="com.rjxy.mybatis.shiyan1.User"> select * from users where id=#{id} </select> </mapper>
What you need to know in Mapper file is the meaning of each attribute in the query tag:
- id: a unique identifier in the namespace that can be used to reference this statement.
- parameterType: the fully qualified name or alias of the class that will pass in the parameters of this statement. (here, we query by id, so the type of the passed in parameter is int)
- resultType: the fully qualified name or alias of the class from which the result is expected to be returned from this statement. (here, we store the query results in the entity class, so the value is the address of the entity class)
There are also some tags and aliases mentioned above, which we will use later.
Step 6:
Since our purpose here is to query, we call the selectOne method in the session, which has two parameters. The first parameter represents the corresponding place of the sql statement, and the second is the parameter required for the query. Returns the result to an entity class object.
Supplement:
MyBatis is a framework based on sql mapping configuration. sql statements are written in Mapper configuration file. When users need it, they need to read the sql configuration in Mapper configuration file. The mappers tag is used to configure the path of the sql mapping configuration file to be loaded. When necessary, users can find the address of the corresponding sql statement through the contents under the label. (the content of config.xml file is as follows)
In the next two lines of code, we need to know:
SqlSession encapsulates operations on the database, such as query, insert, update, delete, etc.
SqlSession is created through SqlSessionFactory.
SqlSessionFactory is created through SqlSessionFactoryBuilder.
To operate the database, we must use the corresponding method in SqlSession.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- Import of database configuration file--> <properties resource="db.properties"></properties> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${name}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/rjxy/mybatis/shiyan1/userMapper.xml"/> </mappers> </configuration>
Step 7
Print out the entity class. Because the toString method is overridden in this entity, it will call the toString method by default to output the queried data.