MyBatis introductory study (5)-MyBatis annotation and operation principle

1. MyBatis Notes

Mybatis annotation can simplify the configuration of mapper.xml. When using annotations, you need to use the <pacakge> tag or <mapper class = ""> tag in the <mappers> tag in the mabatis.xml file

Examples of use:

mybatis.xml

<mappers>
 		<package name="com.xxbb.mapper"/>
 </mappers>

UserMapper.java

public interface UserMapper {
	@Select("select * from t_user limit #{pageStart},#{pageSize}")
	List<User> queryUser(@Param("pageStart") Integer pageStart,@Param("pageSize")  Integer pageSize);

}

Test.java

	UserMapper userMapper=session.getMapper(UserMapper.class);
	Object res= userMapper.queryUser(0,1);
	System.out.println(res);

result

Insert picture description here
Using the @Results tag in the annotation is equivalent to the resultMapper tag in mapper.xml.

@Results(value = {
			@Result(id=true,property = "id",column = "id"),
			@Result(property = "username",column = "username"),
			@Result(property = "password",column = "password"),
			@Result(property = "ifFreeze",column = "if_freeze")
	})
	<resultMap id="UserMap" type="User">
		<id column="id" property="id"/>
		<result column="username" property="username"/>
		<result column="password" property="password"/>
		<result column="if_freeze" property="ifFreeze"/>
	</resultMap>

Second, the operating principle

Take this code as an example

InputStream is=Resources.getResourceAsStream("mybatis.xml");
		SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
		SqlSession session = factory.openSession();

		UserMapper userMapper=session.getMapper(UserMapper.class);
		Object res= userMapper.queryUser(0,1);
1. Classes involved in operation

1.1 Resources-IO stream tool class in MyBatis, used to load configuration files

1.2 SqlSessionFactoryBuilder-builder, used to create the implementation class of SqlSessionFactory interface

1.3 XMLConfigBuilder-MyBatis global configuration file content builder

1.4 Configuration-encapsulates all configuration information of the global configuration file

1.5 DefaultSqlSessionFactory-the implementation class of the SqlSessionFactory interface created by the builder SqlSessionFactoryBuilder

1.6 Transaction-transaction class, every SqlSession will have a Transaction object

1.7 Environment-Get the information in the <environments> tag in the global configuration file

1.8 TransactionFactory-transaction factory, responsible for production transactions

1.9 Executor-MyBatis executor, responsible for executing SQL commands, equivalent to the Statement object in JDBC (or PreparedStatement, CallableStatement)

1.10 DefaultSqlSession-the implementation class of SqlSession interface

1.11 ExceptionFactory-Exception factory in MyBatis

2. Operation flow chart

Insert picture description here

3. Process description

When the MyBatis operation starts, you need to load the global configuration file through the Resources class, and then instantiate the SqlSessionFactoryBuilder builder to help the SqlSessionFactory interface create an implementation class DefaultSqlSesionFactory.

 public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
    try {
      XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
      ErrorContext.instance().reset();
      try {
        reader.close();
      } catch (IOException e) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }
 public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
  }

Before instantiating the DefaultSqlSesionFactory, an XmlConfigBuilder will be created to parse the global configuration file stream, and the analysis result will be placed in the Configuration class. The Configuration object is passed into the DefaultSqlSesionFactory, and the SqlSessionFactory is completed.

 private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
    super(new Configuration());
    ErrorContext.instance().resource("SQL Mapper Configuration");
    this.configuration.setVariables(props);
    this.parsed = false;
    this.environment = environment;
    this.parser = parser;
  }

Create a SqlSession through the SqlSessionFactory. Every time a SqlSession object is created, an environment object is created from the environment information globally configured in the Configuration class. The TransactionFactory receives the Environment object and creates a transaction object. DefaultSqlSession is returned to the SqlSession object.

Transaction tx = null;
    try {
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
      final Executor executor = configuration.newExecutor(tx, execType);
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
Published 35 original articles · praised 7 · 40,000+ views

Guess you like

Origin blog.csdn.net/weixin_44804750/article/details/105086134