1. Introduction to Mybatis
MyBatis is a first-class persistence framework that supports custom SQL, stored procedures and advanced mapping. MyBatis eliminates almost all JDBC code, and there is basically no need to manually set parameters and obtain search results. MyBatis can be configured using a simple XML format or annotations, and can map basic data elements, Map interfaces and POJOs (ordinary Java objects) to records in the database.
2. MyBatis workflow
(1) Load configuration and initialize
Trigger condition: Load configuration file
Configuration comes from two places, one is the configuration file, and the other is the annotation of the Java code. The SQL configuration information is loaded into MappedStatement objects (including the incoming parameter mapping configuration, executed SQL statements, and results). mapping configuration), stored in memory.
(2) Receive call request
Trigger condition: Call the API provided by Mybatis
Incoming parameters: SQL ID and incoming parameter object
Processing process: Pass the request to the lower request processing layer for processing.
(3) Process the operation request. Trigger condition: API interface layer passes the request
Incoming parameters: SQL ID and incoming parameter object
Processing process:
(A) Find the corresponding MappedStatement object based on the SQL ID.
(B) Parse the MappedStatement object according to the incoming parameter object to obtain the final SQL to be executed and the execution incoming parameters.
(C) Obtain the database connection, pass in the final SQL statement and execution parameters to the database for execution, and obtain the execution result.
(D) Convert the execution result obtained according to the result mapping configuration in the MappedStatement object, and obtain the final processing result.
(E) Release connection resources.
(4) Return the processing result and return the final processing result
Basic idea of ORM tools
Whether you have used hibernate or mybatis, you can compare them with one thing in common:
Functional Architecture
The functional architecture of Mybatis is divided into three layers:
1. API interface layer: interface API provided for external use. Developers use these local APIs to manipulate the database. Once the interface layer receives the call request, it will call the data processing layer to complete specific data processing.
2. Data processing layer: Responsible for specific SQL search, SQL parsing, SQL execution and execution result mapping processing, etc. Its main purpose is to complete a database operation according to the calling request.
3. Basic support layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading and cache processing. These are common things, and they are extracted as the most basic components. Provide the most basic support for the upper data processing layer.
More driver packages need to be added:
Here’s a quick start:
The directory is as follows:
Entity class User
package com.oumyye.model; public class User { private String id; private String name; private int age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
Mapping file UserMapping.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.oumyye.mapping.UserMapping"> <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复 使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型 resultType="com.oumyye.model.User"就表示将查询结果封装成一个User类的对象返回 User类就是users表所对应的实体类 --> <!-- 根据id查询得到一个user对象 --> <select id="getUser" parameterType="String" resultType="com.oumyye.model.User"> select * from user where id=#{id} </select> </mapper>
Resource file mybatis.xml
<?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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 配置数据库连接信息 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/oumyye/mapping/userMapping.xml"/> </mappers> </configuration>
Test class:
package test; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import com.oumyye.model.User; public class Tests { @Test public void test(){ String resource = "mybatis.xml"; //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件) InputStream is = Tests.class.getClassLoader().getResourceAsStream(resource); //构建sqlSession的工厂 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession session = sessionFactory.openSession(); /** * 映射sql的标识字符串, * com.oumyye.mapping.UserMapping是userMapper.xml文件中mapper标签的namespace属性的值, * getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL */ String statement = "com.oumyye.mapping.UserMapping.getUser";//映射sql的标识字符串 //执行查询返回一个唯一user对象的sql User user = session.selectOne(statement, "1123"); System.out.println(user.toString()); } }
Result:
The above is a basic tutorial on getting started with the Java Mybatis framework. I hope it will be helpful to everyone's learning.