I. Introduction of MyBatis
MyBatis is a first-class persistence framework that supports custom SQL, stored procedures, and advanced mappings. MyBatis almost eliminates all JDBC code and does not need to manually set parameters and retrieve results. MyBatis can be configured with simple XML formats or annotations that map basic data elements, map interfaces, and POJOs (plain Java objects) to records in the database.
Second, MyBatis work flow
(1) Load Configuration and initialize
Trigger Condition: Load configuration file
Configuration from two places, one is the configuration file, one is the Java code annotations, the SQL configuration information is loaded into a Mappedstatement object (including the incoming parameter mapping configuration, executed SQL statement, result mapping configuration), stored in memory.
(2) Receive call request
Trigger condition: Call the API provided by MyBatis
Incoming parameters: ID for SQL and incoming parameter object
Process: Passes the request to the underlying request processing layer for processing.
(3) Processing operation request trigger conditions: API interface Layer delivery request come over
Incoming parameters: ID for SQL and incoming parameter object
Processing process:
(A) Find the corresponding Mappedstatement object based on the SQL ID.
(B) Parse the Mappedstatement object based on the incoming parameter object to get the final SQL to execute and execute the incoming parameters.
(C) obtain a database connection, based on the resulting SQL statements and execute incoming parameters into the database execution, and get the results of the execution.
(D) Conversion processing of the resulting execution results based on the result mapping configuration in the Mappedstatement object and the resulting processing results.
(E) Release the connection resources.
(4) The return processing result returns the final processing result.
The basic idea of ORM tools
Whether it's used hibernate,mybatis or not, you can have one thing in common:
-
The sessionfactory is obtained from the configuration file (usually in the XML configuration file).
-
Session generated by Sessionfactory
-
In the session to complete the deletion of data and other changes and transaction submissions.
-
Close the session after you are done using it.
-
There is a mapping configuration file between the Java object and the database, usually an XML file.
Functional architecture
MyBatis's functional architecture is divided into three tiers:
-
API Interface Layer: provides interface APIs for external use, where developers manipulate databases through these local APIs. Once the interface layer receives the call request, it invokes the data processing layer to complete the specific data processing.
-
Data processing layer: Responsible for the specific SQL lookup, SQL parsing, SQL execution and execution result mapping processing and so on. Its primary purpose is to complete a database operation at the request of the call.
-
Base Support Layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading and caching processing, these are common things, they are extracted as the most basic components. Provides the most basic support for the data processing layer of the upper layer.
More driver packs to add:
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.) {
This.age = age;
}
@Override
Public String toString () {
Return "User [id=" + ID + ", name=" + name + ", age=" + Age + "]";
}
}
mapping Files 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" >
<!--The SQL statement that writes the query in the Select tab, set the ID property of the Select tag to be unique to the Getuser,id property value and cannot be repeated
Use the ParameterType property to indicate the type of parameter used when querying, and the Resulttype property to indicate the type of result set returned by the query
Resulttype= "Com.oumyye.model.User" means the object that encapsulates the query result as a User class returns
The user class is the entity class corresponding to the Users table
-
<!--
Get a user object based on ID query
-
<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"/>
<!--Configuring database connection Information--
<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";
//Use the ClassLoader to load the MyBatis configuration file (It also loads the associated mapping file)
InputStream is = Tests.class.getClassLoader (). getResourceAsStream (Resource);
//Building a sqlsession factory
Sqlsessionfactory sessionfactory = new Sqlsessionfactorybuilder (). Build (IS);
sqlsession session = Sessionfactory.opensession ();
/**
* Map the identity string of SQL,
* Com.oumyye.mapping.UserMapping is the value of the namespace attribute of the mapper tag in the Usermapper.xml file,
* GetUser is the id attribute value of the select tag, and the value of the id attribute of the SELECT tag can be used to find the SQL to execute
*/
String statement = "Com.oumyye.mapping.UserMapping.getUser";//Mapping SQL identification string
Executes a query that returns the SQL for a unique user object
User user = Session.selectone (statement, "1123");
System.out.println (User.tostring ());
}
}
Results:
Java Mybatis Framework Getting Started tutorial