Mybatis framework research

1 、Mybatis简介

ConfigurationAll configuration information is stored in the Configuration object
SqlSession The top-level API represents the session when interacting with the database, and completes the necessary database addition, deletion, modification, and query functions
ExecutorThe executor is the core of MyBatis scheduling, responsible for SQL statement generation and query cache maintenance
StatementHandlerEncapsulates the JDBC Statement operation
ParameterHandlerResponsible for converting the parameters passed by the user into the data type corresponding to the JDBC Statement
ResultSetHandlerResponsible for converting the ResultSet result set object returned by JDBC into a List type collection
TypeHandlerResponsible for the mapping and conversion between java data types and jdbc data types
MappedStatementMappedStatement maintains a package of <select|update|delete|insert> node
SqlSourceResponsible for dynamically generating SQL statements according to the parameterObject passed by the user, encapsulating the information in the BoundSql object and returning
BoundSql Represents dynamically generated SQL statements and corresponding parameter information

MyBatis hierarchy:

(Image source: "In-depth understanding of mybatis principle" MyBatis architecture design and case analysis , mybatis framework learning )

2. Combination of Mybatis and SpringBoot

Source of source code:

1. Create a maven project first, build the directory and then import it into the compiler. The advantage of this is that you can change the parameters later and you can use it in each project.

<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">    <modelVersion>4.0.0</modelVersion>    <groupId>com.boot</groupId>    <artifactId>testSpringBoot</artifactId>    <version>0.0.1-SNAPSHOT</version>    <name>testSpringBoot</name>    <packaging>jar</packaging>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>1.5.9.RELEASE</version>        <relativePath/>    </parent>    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>                <!-- mybatis依赖 -->        <dependency>            <groupId>org.mybatis.spring.boot</groupId>            <artifactId>mybatis-spring-boot-starter</artifactId>            <version>1.3.1</version>        </dependency>                <!-- 引入thymelaf 则不需要引入web依赖,若不需要thymelaf则需要添加spring-boot-starter-web -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-thymeleaf</artifactId>        </dependency>                <!-- mysql依赖 -->        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>        </dependency>                 <dependency>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-starter-test</artifactId>        </dependency>    </dependencies>    <build>    <plugins>        <!-- 要使生成的jar可运行,需要加入此插件 -->        <plugin>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-maven-plugin</artifactId>        </plugin>    </plugins></build></project>

2. Startup

To develop any Spring Boot project, the above startup classes will be used. Mainly @SpringBootApplication annotation
and function. Explain briefly:

The @SpringBootApplication annotation is the core annotation of Spring Boot. It is actually a composite annotation:

@ComponentScan(excludeFilters = {          @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),          @Filter(type = FilterType .CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication { ... }

Three of the more important ones are:

@SpringBootConfiguration (essentially uses @Configuration, the configuration class of the Spring Ioc container in the form of JavaConfig)
@EnableAutoConfiguration (automatically scans and loads qualified components or bean definitions, and finally loads these bean definitions into the IoC container)
@ComponentScan (with the help of @Import support, collect and register bean definitions related to specific scenarios.)

3. Database

1) corresponds to the table fields in the table word database

2) DAO interface

3) Service interface class and implementation class

4. Mapper

Corresponding to the dao file, containing SQL query statements

5. Resource allocation

1) Spring-boot configuration


2) Log printing logback-spring.xml

6. Testing

Select the test class, right-click run as and select Junit Test

7. Web page

control class

3. Combination of Mybatis and Maven

Mybatis is configured by using xml or annotations to automatically map the parameters in the java object and the sql statement to generate the final executed sql statement, and automatically map the execution result of the sql statement to a java object and return it to the service application.

1 Configure in pom.xml in maven

<dependency>	<groupId>org.mybatis</groupId>	<artifactId>mybatis</artifactId>	<version>${mybatis.version}</version></dependency>

2. The mybatis framework requires a core configuration file named sqlmybatis.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-// Config 3.0//EN" "">	    <!-- 运行环境配置 -->    <!--default属性:指定使用哪一个运行环境  -->    <environments default="development">        <!--id属性:唯一标识一个运行环境  -->        <environment id="development">            <!-- 事务管理器配置,type="JDBC":mybatis框架默认使用jdbc事务 -->            <transactionManager type="JDBC"/>             <!--数据源配置,type="POOLED":mybatis框架提供的连接池  -->            <dataSource type="POOLED">                <property name="driver" value="com.mysql.jdbc.Driver"/>                <property name="url" value="jdbc:mysql://"/>                <property name="username" value="root"/>                <property name="password" value="root"/>            </dataSource>        </environment>    </environments>	<!-- 加载映射文件 -->	<mappers>		<mapper resource="UserMapper.xml"/>	</mappers></configuration>

3. Implement UserMapper.xml file

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-// Mapper 3.0//EN" ""><mapper namespace="mybatis">	<!-- 新增用户 -->	<insert id="addUser" parameterType="com.learn.mybatis.domain.UserBeen">		insert into user (id,username,birthday)		values (#{id},#{username},#{birthday})	</insert>		<!-- 根据用户id删除用户 -->	<delete id="deleteUser" parameterType="int">		delete from user where id = #{id}	</delete>		<!-- 根据用户id修改用户 -->		<!-- 根据id查询 -->		<!-- 方式一:根据用户名称模糊查询用户 -->	<select id="queryUserByName1" parameterType="string" resultType="com.learn.mybatis.domain.UserBeen">		select id,username,birthdayfrom `user` where username like  #{username}	</select>		<!-- 方式二:根据用户名称模糊查询用户 -->	<select id="queryUserByName2" parameterType="string" resultType="com.learn.mybatis.domain.UserBeen">		select id,username,birthday from `user` where username like  '%${value}%'	</select>		</mapper>

3. class implementation

package com.learn.mybatis.domain; import java.util.Date; public class User {	private Integer id; // 主键id	private String username; // 用户名称	private Date birthday; // 生日		public Integer getId() {		return id;	}	public void setId(Integer id) { = id;	}	public String getUsername() {		return username;	}	public void setUsername(String username) {		this.username = username;	}	public Date getBirthday() {		return birthday;	}	public void setBirthday(Date birthday) {		this.birthday = birthday;	}		@Override	public String toString() {		return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + " ]";	}	 }

4. Test class implementation

public class MyBatisTest {     public SqlSessionFactory getSqlSessionFactory() throws IOException {		// 1.加载核心配置文件		InputStream inputStream = Resources.getResourceAsStream("sqlmybatis.xml");		// 2.读取配置文件的内容		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();		SqlSessionFactory sqlSessionFactory =; 		return sqlSessionFactory;	}       public void addUser() throws IOException {				SqlSession sqlSession = this.getSqlSessionFactory().openSession(true);				UserBeen user = new UserBeen();		user.setId(1);		user.setUsername("test");		user.setBirthday(new Date());		sqlSession.insert("mybatis.addUser", user);		// 事务提交		// sqlSession.commit();		// 释放资源		sqlSession.close();	}     public void queryUserById() throws IOException {				SqlSession sqlSession = this.getSqlSessionFactory().openSession();				Object user = sqlSession.selectOne("mybatis.queryUserById", 2);				sqlSession.close();	}     public void queryUserByName1() throws IOException {				SqlSession sqlSession = this.getSqlSessionFactory().openSession();				List<Object> userList = sqlSession.selectList("mybatis.queryUserByName1", "%test%");		for (Object object : userList) {			System.out.println(object);		}				sqlSession.close();	} 

Note: The placeholder #{} is equivalent to the question mark in jdbc? , Which is pre-compiled