Simple use of Mybatis framework

Posted by VK4KBG on Fri, 10 May 2019 03:06:03 +0200

1. Configuration process

1. Process diagrams (implemented through XML mapping files):

2. Process:

2.1 Import package:
2.1.1 Download Package

Database Driven Package (this article takes MySQL as an example): https://mvnrepository.com/artifact/mysql/mysql-connector-java

Mybatis Framework Package: https://mvnrepository.com/artifact/org.mybatis/mybatis

 

2.1.2 Importer

Put the jar package in a new folder created by the program

  

Select the jar package and right-click Build Path->Add to Build Path. As a result, the jar package is loaded in the process as shown in the figure

 

2.2 Add Rule File

Location of rule file: 1\mybatis-3.4.1\org\apache\ibatis\builder\xml

(2) Open the Mybatis Framework folder downloaded above and look for dtd

 

Key of the rule file: Ctrl+F finds public in the official document:

 

 

 

Select Window->Preferences

Click OK, repeat the above operation, and finish adding the Mapper rule file.

 

2.3. Write configuration files
2.3.1 Create an XML file

Create an XML file under the src file, fill in the file named MybatisConfig.xml, and Next:

Select the DTD file and Next,

 

Select Create Profile and Next->FInish to create successfully.

 

2.3.2 Writing Files
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd" >
 3 <configuration>
 4 <!--The environments tag is used to configure database connection information and can configure connection information for multiple databases  
 5 default property: Multiple database connection environments can be configured in the environment set, but the default environment must be specified, which is the ID of the environment label
 6     -->
 7     <environments default="sms">
 8 <!-- Environment label, information for configuring a database connection-->
 9         <environment id="sms">
10 <!--Specify the type of transaction to use 
11 JDBC: Transaction using JDBC
12 MANAGER: Transaction not required
13             -->
14             <transactionManager type="JDBC"></transactionManager>
15 <!--dataSource tag: Configure database connection information
16 type: Configure the type of data source
17 JNDI: Using a JNDI data source means configuring the data source on the web server so that the program can call it
18 POOLED: Use default built-in connection pool
19 UNPOOLED: No connection pooling is required using a direct connection database
20              -->
21             <dataSource type="POOLED">
22 <!--Connect the four elements-->
23                 <property name="driver" value="org.gjt.mm.mysql.Driver"/>
24                 <property name="url" value="jdbc:mysql://localhost:3306/sms"/>
25                 <property name="username" value="root"/>
26                 <property name="password" value="12345"/>
27             </dataSource>
28         </environment>
29     </environments>
30 <!--Configure the specified loaded mapping file-->
31     <mappers>
32         <mapper class="cn.zwj.mapper.StudentMapper"></mapper>
33     </mappers>
34 </configuration>
MybatisConfig.xml

 

2.4 Mapping Files and Mapping Interfaces

Since the mapping file and the mapping interface have to correspond, their corresponding relationship is represented by the same name, and the corresponding interface can be found well in multiple mapping files.

Create a mapping file,

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" >
<mapper namespace="cn.zwj.mapper.StudentMapper">
    <!-- #{} Similar?(preprocessing block), corresponding to the variable name in POJO-->
    <insert id="insert">
        INSERT INTO tb_student (STUDENT_NAME, STUDENT_PWD, STUDENT_STATUS, CREATE_DATE, STUDENT_ACCOUNT) VALUES (#{studentName}, #{studentPwd}, #{studentStatus}, #{createDate}, #{studentAccount})
    </insert>
</mapper>
StudentMapper.xml
1 package cn.zwj.mapper;
2 
3 import cn.zwj.pojo.Student;
4 
5 public interface StudentMapper {
6     int insert(Student student);
7 }
StudentMapper.java

The corresponding interface is bound by the namespace attribute of the <mapper>tag in the XML, and the id attribute value of the <insert>tag is the method name in the excuse

 

2.5 POJO
 1 import java.io.Serializable;
 2 import java.util.Date;
 3 
 4 public class Student implements Serializable{
 5     private static final long serialVersionUID = -9125884258413809899L;
 6     public Long studentId;//bigint(20) not null auto_increment comment 'Student Number',
 7     public String studentName;//varchar(50) null default null comment 'Full name',
 8     public String studentPwd;//varchar(50) null default null comment 'Password',
 9     public Integer studentStatus;//int(11) null default null comment 'state',
10     public Date createDate;//datetime null default null comment 'Creation Time',
11     public String studentAccount;//varchar(50) null default null comment 'Student Account Number',
12     public Long getStudentId() {
13         return studentId;
14     }
15     public void setStudentId(Long studentId) {
16         this.studentId = studentId;
17     }
18     public String getStudentName() {
19         return studentName;
20     }
21     public void setStudentName(String studentName) {
22         this.studentName = studentName;
23     }
24     public String getStudentPwd() {
25         return studentPwd;
26     }
27     public void setStudentPwd(String studentPwd) {
28         this.studentPwd = studentPwd;
29     }
30     public Integer getStudentStatus() {
31         return studentStatus;
32     }
33     public void setStudentStatus(Integer studentStatus) {
34         this.studentStatus = studentStatus;
35     }
36     public Date getCreateDate() {
37         return createDate;
38     }
39     public void setCreateDate(Date createDate) {
40         this.createDate = createDate;
41     }
42     public String getStudentAccount() {
43         return studentAccount;
44     }
45     public void setStudentAccount(String studentAccount) {
46         this.studentAccount = studentAccount;
47     }
48 }
Student.java

Entity class corresponding to a table in the database, implementing set/get method

 

2.6 Session Building Tool Class
 1 import java.io.IOException;
 2 import java.io.Reader;
 3 
 4 import org.apache.ibatis.io.Resources;
 5 import org.apache.ibatis.session.SqlSession;
 6 import org.apache.ibatis.session.SqlSessionFactory;
 7 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 8 
 9 public class MybatisUtils {
10     //Open only one factory to the outside world
11     public static final SqlSessionFactory SSF = createSqlSessionFactory();
12     //Declare a thread variable
13     public static final ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<>();
14     
15     //1.Get Session Factory
16     private static SqlSessionFactory createSqlSessionFactory() {
17         try {
18             //Read Configuration File
19             Reader reader = Resources.getResourceAsReader("MybatisConfig.xml");
20             //Create Session Factory Build Class Object
21             SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
22             //Build Session Factory
23             return builder.build(reader);
24         } catch (IOException e) {
25             // TODO Auto-generated catch block
26             e.printStackTrace();
27         }
28         return null;
29     }
30     
31     //2.Get Sessions
32     public static SqlSession getSession() {
33         if (THREAD_LOCAL.get() == null) {
34             SqlSession session = SSF.openSession();
35             THREAD_LOCAL.set(session);
36         }
37         return THREAD_LOCAL.get();
38     }
39     
40     public static void close() {
41         if (THREAD_LOCAL.get() != null) {
42             SqlSession session = THREAD_LOCAL.get();
43             session.close();
44             THREAD_LOCAL.remove();
45         }
46     }
47 }
MybatisUtils.java

Why only open one factory to the outside world?

A: Because if there are multiple data sources, the connection to the database may come from different data sources!Causes database connections to fail to synchronize, causing transactions to fail!

Why declare a thread variable?

Answer: The same session as a thread accessed, thread-safe

 

2.7. Testing
 1 import org.apache.ibatis.session.SqlSession;
 2 import org.junit.Test;
 3 
 4 import cn.zwj.mapper.StudentMapper;
 5 import cn.zwj.pojo.Student;
 6 import cn.zwj.utils.MybatisUtils;
 7 
 8 public class StudentTest {
 9     @Test
10     public void test1() {
11         //Get Sessions
12         SqlSession session = MybatisUtils.getSession();
13         //Building dynamic objects for mapping interfaces
14         StudentMapper studentMapper = session.getMapper(StudentMapper.class);
15         Student student = new Student();
16         student.setStudentName("Zhang San 1");
17         int insert = studentMapper.insert(student);
18         System.out.println(insert);
19         //Submit Transaction
20         session.commit();
21         MybatisUtils.close();
22     }
23 }
Test.java

When the console outputs a number greater than 0, the database is successfully operated using the mybatis framework

 

2.8 Modified to Annotation Implementation
2.8.1 Flow Diagram:

2.8.2 Modify Code:
 1 import org.apache.ibatis.annotations.Insert;
 2 import org.apache.ibatis.annotations.Options;
 3 
 4 import cn.zwj.pojo.Student;
 5 
 6 public interface StudentMapper {
 7     @Insert("INSERT INTO tb_student (STUDENT_NAME, STUDENT_PWD, STUDENT_STATUS, CREATE_DATE, STUDENT_ACCOUNT) VALUES (#{studentName}, #{studentPwd}, #{studentStatus}, #{createDate}, #{studentAccount})")
 8     @Options(useGeneratedKeys = true, keyProperty = "studentId")
 9     //@Options: Annotation declaration generates primary key
10     int insert(Student student);
11 }
StudentMapper.java
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd" >
 3 <configuration>
 4     <environments default="sms">
 5         <environment id="sms">
 6             <transactionManager type="JDBC"></transactionManager>
 7             <dataSource type="POOLED">
 8                 <property name="driver" value="org.gjt.mm.mysql.Driver"/>
 9                 <property name="url" value="jdbc:mysql://localhost:3306/sms"/>
10                 <property name="username" value="root"/>
11                 <property name="password" value="12345"/>
12             </dataSource>
13         </environment>
14     </environments>
15         <!-- Modify Mapping File to Mapping Interface-->
16     <mappers>
17         <mapper class="cn.zwj.mapper.StudentMapper"></mapper>
18     </mappers>
19 </configuration>
MybatisConfig.xml

Delete the mapping file and test the code.

Topics: Java Session xml Mybatis Database