Syria : This is what I learned before mybatis The notes , More detail , Because some of the previous study notes were mistakenly deleted on the computer , So just sort it out and save it online , Also hope to help some children's shoes ~

Mybatis The whole process of novice project construction — Personal study notes - Hyperdetail

  • 1、MyBatis What is the framework ?
  • 2、MyBatis What is it for ?
  • 3、MyBatis Basic configuration ( dried food )
    • 3.1、 Create a new project
    • 3.2、 The project needs to introduce Jar package
    • 3.3、 Create database tables
    • 3.4、 Framework configuration file
    • 3.5、 establish POJO object
    • 3.6、 Write test code
    • 3.7、 test
  • 《END》

First , We need to know MyBatis What is the framework ? What is it for ? Then you need to learn how to use it , Finally, you need to know why it works like this , Next, I will use this idea to record my study notes ;

1、MyBatis What is the framework ?

MyBatis This is a apache An open source project of iBatis, 2010 This project was initiated by apache software foundation Moved to google code, And renamed it MyBatis .2013 year 11 Month to migrate to Github( I think this is MyBatis The framework wants to further promote , One step towards world class usage ).
iBATIS The word comes from “internet” and “abatis” The combination of , It's based on Java The persistence layer framework .iBATIS The persistence layer framework provided includes SQL Maps and Data Access Objects(DAOs).

2、MyBatis What is it for ?

MyBatis It's based on Java The persistence layer framework , This is its essence , To put it bluntly, it means to be with Hibernate Framework exists for the same purpose , It's all about operating databases ( And the reason why there is Hibernate This ORM Data persistence layer framework will be born MyBatis It's because they have different priorities , I won't go into details here ;)

3、MyBatis Basic configuration ( dried food )

Understand the meaning of this framework , Then we have the purpose to learn from him , Let's start with MyBatis Learning at the entry level , First, configure to run through a MyBatis Environmental Science , Generally, there are several steps to complete the configuration of a framework environment : One 、 Create a new project ; Two 、 What you need to import the framework Jar package ; 3、 ... and 、 Create database tables ; Four 、 Create a framework configuration file ( In general, there are more or less file item configurations in frameworks ); 5、 ... and 、POJO establish ; 6、 ... and 、 Write test code ;
I understand the general process , Walk up ~

3.1、 Create a new project

Creating a project doesn't have to be too much , Just look at the screen capture ;
 Insert picture description here
What I use is jar Bag for jdk Ask for in 1.7 Or more , So I use 1.8 Of jdk, Pay attention to the use of jar Bao He jdk Does the version of fit ;
The created project , Here's the picture :
 Insert picture description here
The composition of the project is only src and JRE System Library These two bags , Next, we can create the required packages manually ;

3.2、 The project needs to introduce Jar package

Jar The location of the package needs to be created manually , Create a project named lib Of Folder Folder , It's dedicated to our jar package , Here's the picture :
 Insert picture description here
Create as follows :
 Insert picture description here
Now? jar The file path of the package has been created , We need to look at our own jar What's in the bag ?

  1. First of all MyBatis Of jar package , only one :mybatis-3.5.4.jar( There is a post below the path to download the file );
  2. Other jar package ( for example : Log package 、 Connect to database package, etc );

Mybatis The download path of the framework package is as follows , There are various versions of jar package :
 Insert picture description here
Get into :
 Insert picture description here
Other needs jar The package is shown in the figure below :
 Insert picture description here
Put it all together 11 individual jar After the package is imported, select all of them and do it , Here's the picture :
 Insert picture description here
After adding it, it's as follows :
 Insert picture description here
Here we are , Project jar The package is introduced ;

3.3、 Create database tables

Mybatis Introduction learning , Database tables don't have to be that complicated , So let's set up a User surface , My database name is :mybatis, The coded character set is UTF-8 Of , And then it creates User Data sheet , Its operation SQL The data are as follows :

  `uuid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' user id',
  `username` varchar(12) NOT NULL COMMENT ' User name ',
  `birthday` date DEFAULT NULL COMMENT ' Date of birth ',
  `address` varchar(20) DEFAULT NULL COMMENT ' Current address ',
  `gender` varchar(1) NOT NULL COMMENT ' Gender ',

Created user Insert a piece of data after the data table , Insert SQL as follows :

INSERT `user`VALUES('1','ba6567ac-8f41-11ea-b8d9-fc459696f733',' test ','1989-04-20',' three countries ','0')

Running results :

Refresh the table and see the corresponding data ;

3.4、 Framework configuration file

Mybatis There are two main configuration files , One is to configure database data ( There is only one project ), The other is configuration POJO Data objects are mapped to databases SQL Of the statement ( One project has N individual , In principle, every POJO Each has its own configuration file like this ); And these two kinds of configuration files generally try to put them together , Create a folder , The naming requirement is not high , But it needs to be easy to understand , It can be used in general config 、xml etc. , This folder can be stored in the project name , and src The folder is on the same level , Here's the picture :
 Insert picture description here

  • The first one is— Log profile
    This file doesn't need us to create , But you need to download it from the Internet, copy and paste it into the package , Download url ( Non official website , Close test available ):
  • Second, manually created configuration files :sqlMapconfig.xml
    This is a core profile , There is only one configuration file in a project , The configuration content is also very simple , Is to set and specify which data connection configuration to use , The code and its comments are as follows :
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration
PUBLIC "-// Config 3.0//EN"""><configuration><!--  and spring After integration  environments Configuration will be abolished  --><environments default="development"><!--  development environment  --><environment id="development"><!--  Use jdbc Business management  --><transactionManager type="JDBC" /><!--  Database connection pool  --><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url"
					value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" /><property name="username" value="root" /><property name="password" value="root" /></dataSource></environment><!--  Test environment  --><environment id="test"><!--  Use jdbc Business management  --><transactionManager type="JDBC" /><!--  Database connection pool  --><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url"
					value="jdbc:mysql://localhost:3306/mybatisTest?characterEncoding=utf-8" /><property name="username" value="root" /><property name="password" value="root" /></dataSource></environment></environments><mappers><mapper resource="mybatis/user.xml" /></mappers></configuration>

among configuration In the tag default Property refers to switching the connected database when there are databases with multiple environments , Database links in different environments need to be in <environment id="xxx"> Of id To configure , adopt Id To distinguish ;
<mapper resource="mybatis/user.xml" /> The code is the one that will follow POJO Object's SQL The configuration file loads in , Write it in advance ;

  • Create a second profile :user.xml
    This is aimed at POJO To the database sql Configuration file for Relationship Mapping , In a nutshell, it's in POJO What happens on the object SQL The events are finally written in this POJO In the configuration file of , In general, there will be multiple such configuration files with different names , So create a new package in the package for these files , To store this type of document , Create as follows :
     Insert picture description here
    Then create a user.xml file , The code in the file is as follows :
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper
PUBLIC "-// Mapper 3.0//EN"""><mapper namespace="user"><!--  Code below the comments  --></mapper>

After creation, associate this file with mybatis In the core configuration file of , That's it. <mapper resource="mybatis/user.xml" />; Note that the import path starts with the core configuration file ;

3.5、 establish POJO object

I mentioned it all the time POJO object , Now it's time to create , First , stay “src” Create a POJO Folder , Used exclusively for storage POJO Object's , Then in this folder, according to the database table created before user surface , To write The code is as follows :

package;import java.util.Date;public class User {private int id;private String uuid;private String username;//  User name private String gender;//  Gender private Date birthday;//  Birthday private String address;//  Address public int getId() {return id;}public void setId(int id) { = id;}public String getUuid() {return uuid;}public void setUuid(String uuid) {this.uuid = uuid;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getSex() {return gender;}public void setSex(String sex) {this.gender = sex;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "\n  The user id :" + id + ",  Unique identification code :" + uuid + ",  name :" + username				+ ",  Gender :" + gender + ",  Date of birth :" + birthday				+ ",  Address :" + address + "\n" ;}}

3.6、 Write test code

To write user Object's test code , First of all, make sure that we want to achieve the goal of user What is the function of this object , And the main code to implement the function is actually SQL operation , therefore , We first in user Object's SQL The configuration file user.xml Related operations in the file ;

  • Test code function : Inquire about ID by “ 1 ” Of user User information ;
  • user.xml The code in the file :
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper
PUBLIC "-// Mapper 3.0//EN"""><mapper namespace="user"><!-- id: This article SQL Unique identifier of           parameterType: Passed in parameter type          resultType: Return result type   --><select id="getUserById" parameterType="int" resultType=""><!-- #{}: Place holder , Equivalent to JDBC Of '?' Place holder  --><!--  If the incoming data type is a normal data type , It can be filled at will  -->
		SELECT * FROM `user` u WHERE #{id}</select></mapper>

  • class In the document Test Code :
package;import;import;import;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test;import;public class TestClass {/**
	 *  adopt ID Query user information 
	 * @throws IOException
	 */@Testpublic void TestGetUserById() throws IOException{//  establish SqlSessionFactoryBuilder object 
		SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();//  Create and get sql Statement configuration file input stream object 
		InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");//  Use sql Statement configuration file with input stream object SqlSessionFactoryBuilder objects creating sqlSessionFactory(sqlsession factory ) object 
		SqlSessionFactory sqlSessionFactory =;//  establish sqlsession The object of the factory        true: Turn on auto commit transactions 
		SqlSession openSession = sqlSessionFactory.openSession(true);//  Get user information 
		User userObj = openSession.selectOne("user.getUserById", 1);
		System.out.println(userObj);//  Release resources 

3.7、 test

The test results are as follows :
 Insert picture description here
You can see a lot of information in the log , for example : Create a connection number 、SQL sentence 、 Pass in parameters and their types 、 The number of results 、 Result display 、 close JDBC Connect 、 Return connection to connection pool, etc .

That's all Mybatis The basic process of building the framework , Further notes are still being compiled , What I wrote before , Now we need to run it again to make sure it's safe ~

pass: There are shortcomings , I hope you guys are right ~