mybatis study notes (Diary)

The core object of MyBatis

SqlSessionFactory is a very important object in the Mybatis framework. It is a compiled memory image of a single database mapping relationship. Its main function is to create an instance of SqlSession.SqlSessionFactory object, which can be built through SqlSessionFactoryBuilder object.

The code is as follows:

		//Define profile
String resource="mybatis-config.xml";  
			//Read configuration file
Reader reader = Resources.getResourceAsReader(resource);
			//Construction factory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

The SqlSessionFactory object thread is safe. Once it is created, it will exist throughout the execution of the application. Generally, each database only corresponds to one SqlSessionFactory, so it is recommended to use singleton mode when building SqlSessionFactory instances

It is also important that the SqlSessionFactory object has an openSession() method. It will return a SqlSession, and the instance cannot be shared;

SqlSession is a single threaded object that performs interactive operations between the persistence layers of the application domain. Its main function is to perform persistence operations. In addition, SqlSession also contains all SQL operation methods in the database. Because JDBC links are installed at the bottom, its instances can be directly used to execute mapped SQL statements.

There are two uses of SqlSession:

1: String form (I prefer the second)

   //                 Configuration file path + selectId value query value returns a single object
SqlSession.selectOne("edu.gdkm.commern.selectByName","Zhang San")
   //                 Configuration file path + selectId value query value returns collection object
SqlSession.selectList("edu.gdkm.commern.selectByNames","Zhang");

2: Getmapper (class < T > type)

SqlSession session = MybatisUtils.getSession();
//There are two files here. One is the CustomerMapper.java interface, and the other is CustomerMapper.xml. The name must be the same and under the same package
CustomerMapper mapper = session.getMapper(CustomerMapper.class);
/**
In this way, the instance object mapper of CustomerMapper can call the methods of the CustomerMapper interface
 However, it should be noted that some methods in the CustomerMapper interface should also set the same id in the CustomerMapper.xml file, and the return value and formal parameters should be consistent*/

Mybatis configuration file

In the Mybatis core configuration file, the < configuration > element is the root element of the configuration file.

In < configuration >

<properties,<settings>,<typeAliases>,<typeHandlers>,<objectFactory>,<plugins>,<environments>,<databaseIdProvider>,<mappers>

There are sub elements < environment > in < environments >

The sub elements of < environment > are: < transactionmanager >, < datasource >

It should be noted that the child elements of configuration must be configured in order, otherwise Mybatis will make an error when parsing the XML configuration file. < Properties > is the first and < mappers > is the last.

<properties>

There are two ways to configure database connection properties   You can write the link mode directly to the Mybatis configuration file, or create a new properties file outside.

Mode 1:

  <environments default="mysql8">
        <!--1.2.to configure id by mysql Database environment -->
        <environment id="mysql5">
            <!-- use JDBC Transaction management -->
            <transactionManager type="JDBC" />
            <!--Database connection pool -->
            <dataSource type="POOLED">
              <!-- mysql5.7 following -->	            
 			  <property name="driver" value="com.mysql.jdbc.Driver" />
			  <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;serverTimezone=GMT%2B8" /> 
			  <property name="username" value="654321" />
			  <property name="password" value="123456" />
            </dataSource>
        </environment>
  </environments>

Mode 2:

First, create a new db.properties under src

db.properties content display:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false&amp;serverTimezone=GMT%2B8
jdbc.username=654321
jdbc.password=123456
<properties resource="db.properties"/>   
 <environments default="mysql8">
        <environment id="mysql8">
            <!-- use JDBC Transaction management -->
            <transactionManager type="JDBC" />
            <!--Database connection pool -->
            <dataSource type="POOLED">
              <!-- mysql8 -->
 			  <property name="driver" value="${jdbc.driver}" />
			  <property name="url" value="${jdbc.url}" /> 
			  <property name="username" value="${jdbc.username}" />
			  <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>

<settings>

It is mainly used to change the behavior of MyBatis runtime, such as enabling L2 cache and delayed loading. The following is a configuration case of printing logs on the console

First create a new log4j.properties file and write the configuration content

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.edg.gdkm=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - [\u65E5\u5FD7\u4FE1\u606F]%m%n
	<settings>
		<!-- use LOG4J journal -->
		<setting  name="logImpl"  value="LOG4J" />
	</settings>

<typeAliases>

Give the java type a short name, that is, set an alias;

<typeAliases>
// The alias attribute is an alias and the type attribute is a type
<typeAlias  alias="user" type="com.gdkm.fmt.User"/>
//When there are too many POJO classes, you can also customize the alias by automatically scanning the package
<package name="com.gdkm.fmt"/>
</typeAliases>

If the package is used, Mybatis will take the POJO class in the com.gdkm.fmt package as its alias with a lowercase unqualified class name. For example, the alias of com.gdkm.fmt.User is user, and the alias of com.gdkm.fmt.comment is comment.

It should be noted that the above alias can only be used without annotation, and the annotation name needs to be used after annotation;

<typeHandler>

The function of typeHandler is to convert the parameters passed in the preprocessing statement from javaType(JAVA type) to JDBC type (JDBC type), or convert JDBC type to javaType when fetching the results from the database

1. Register the type processor of a class

<typeHandlers>
<--Configure as a single class handler Specifies the processor type customized in the program-->
<typeHandler handler="com.gdkm.fmt.User">
</typeHandlers>

2. Register the processor type of a package

<typeHandlers>
<!--Register all in a package TYPEHANDLER,The system will automatically scan all files under the package at startup-->
<package name="com.gdkm.fmt"/>
</typeHandlers>

<objectFactory>

Custom factory / / supplement later

<plugins>

plugins is used to configure plug-ins developed by users.

<environments>

The environments element configures the environment. The environment configuration of MyBatis is actually the configuration of data sources. We can also configure multiple data sources through the < environments > element, that is, configure multiple databases

The cases are as follows:

    <!--1.Configure environment, default environment id by mysql-->
    <environments default="mysql8">
        <!--1.2.to configure id by mysql Database environment -->
        <environment id="mysql5">
            <!-- use JDBC Transaction management -->
            <transactionManager type="JDBC" />
            <!--Database connection pool -->
            <dataSource type="POOLED">
              <!-- mysql5.7 following -->	            
 			  <property name="driver" value="com.mysql.jdbc.Driver" />
			  <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;serverTimezone=GMT%2B8" /> 
			  <property name="username" value="654321" />
			  <property name="password" value="123456" />
            </dataSource>
        </environment>
        <environment id="mysql8">
            <!-- use JDBC Transaction management -->
            <transactionManager type="JDBC" />
            <!--Database connection pool -->
            <dataSource type="POOLED">
              <!-- mysql8 -->
 			  <property name="driver" value="${jdbc.driver}" />
			  <property name="url" value="${jdbc.url}" /> 
			  <property name="username" value="${jdbc.username}" />
			  <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>

Two types of transaction managers can be configured in Mybatis: JDBC and MANAGED

JDBC: this configuration directly uses JDBC's commit and rollback settings. It depends on the link obtained from the data source to process the scope of the transaction.

MANAGED: this configuration never commits or rolls back a link, but lets the container manage the entire life cycle of the transaction. By default, it will close the link, but some containers do not want this. Therefore, you can set the closeConnection property to false to prevent its default closing behavior.

If Spring+MyBatis is used in the project, there is no need to configure the transaction manager in MyBatis, because in actual development, Spring's own manager will be used to realize transaction management.

Data sources are configured with unpooled, pooled and JNDI

<mappers>

The < mappers > configuration file is used to specify the location of the Mybatis mapping file. There are generally four ways:

1. Use classpath to import

<mappers>
<mapper resource="com/gdlm/fmt/UserMapper.xml">
</mappers>

2. Import using local file

<mappers>
<mapper url="file:///D:/com/gdlm/fmt/UserMapper.xml">
</mappers>

3. Use interface class to import

<mappers>
<mapper class="com.gdkm.fmt.UserMapper">
</mappers>

4. Use package name reference

<mappers>
<mapper package="com.gdkm.fmt">
</mappers>

Choose which method to use according to the situation, but no matter how you look, it is the fourth convenience! (I think)

mapper profile

There are select, insert, update, delete, SQL, cache, cache ref and resultmap

1. < Select > query

 <select id="selectS" parameterType="Integer" resultType="edu.gdkm.po.Customer">
select * from t_tbale where id=#{value}
</select>

2. < Insert > insert

<insert id="insertByComm" parameterType="edu.gdkm.po.Customer">
insert into t_tbale(name,age,josh) values ("asdsad",16,"123213")
</insert>

3. < updata > Modify

<updata id="updByComm" parameterType="edu.gdkm.po.Customer">
Modified sql sentence
</updata>

4.sql is used to define some sql, which can be referenced by other statements

<!--definition sql-->
<sql id="BMK_LIST">
id,name,age,josh
</sql>

 <select id="selectByUser" parameterType="edu.gdkm.po.Customer" resultType="edu.gdkm.po.Customer">
select 
<!--Call the defined sql-->
<include refid="BMK_LIST"/>
 from t_tbale where id=#{id}
</select> 

The refid attribute of include is the id of sql.

5.cache configuration for namespace

6. Cache ref references to other namespace cache configurations

7.resultMap is used to describe how to load objects from database results

The resultMap element represents the result map set.

Tags: Database Mybatis SQL

Posted on Sun, 24 Oct 2021 00:48:14 -0400 by Jeller