MyBatis is an excellent persistence layer framework, which supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all JDBC code, manual parameter setting and result set retrieval. MyBatis can use simple XML or annotations to configure and map native information, map interfaces and Java POJOs (Plain Old Java Objects) to records in the database, and generate freely and flexibly (semi-automatic, most of which require programmers to write sql).

Official documents of Mybatis: http://www.mybatis.org/mybatis-3/zh/index.html

1、 Frame principle:

mybatisconfig.xml : (It is the global configuration file of mybatis, and the name is not fixed) The mybatis running environment such as data source and transaction is configured
mapper.xml : Configure sql statements
SqlSessionFactory : (session factory), create a factory according to the configuration file Role: create a SqlSession
SqlSession : (session), is an interface for users (programmers). Its function is to operate the database (issue sql add, delete, modify, and query)
Executor : (actuator), which is an interface (basic actuator, cache actuator). Function: SqlSession operates the database through the actuator internally
mapped statement : (Bottom encapsulation object) Function: Encapsulates the operation database storage, including sql statements, input parameters, and output result types.
 Mybatis from beginner to proficient (I)

2、 Getting Started

1) Environment:
Jdk1.8, mysql5.6, IDEA, necessary jar package
If you use maven, you can use the following AVG import (currently select version 3.4.5):

 <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency>

2) Create the necessary configuration files:
Log4j. properties (log4j log configuration file):

 #Initialize definition log level log4j.rootLogger=DEBUG,Console #Output to console log4j.appender. Console=org.apache.log4j. ConsoleAppender log4j.appender. Console.layout=org.apache.log4j. PatternLayout log4j.appender. Console.layout. ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.org.apache=INFO

Mybatis-config.xml (mybatis configuration file):

 <? 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> <properties resource="jdbc.properties" /> <settings> <!-- Set automatic hump naming conversion --> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!--  After integration with spring, the environment configuration will be abolished --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <!-- Load mapping file --> <mapper resource="com/lcry/mybatis/dao/EmployeeMapper.xml"/> </mappers> </configuration>

Jdbc. properties (database information configuration):

 driver=com.mysql.jdbc. Driver url=jdbc: mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf -8 username=root password=123456

Employee. java (entity class):

 package com.lcry.mybatis.bean; public class Employee { private  Integer id ; private  String lastname;  // There is a pit here private  String email; private  String gander;  // There is a pit here public Integer getid() { return id; } public void setId(Integer id) { this.id = id; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGander() { return gander; } public void setGander(String gander) { this.gander = gander; } @Override public String toString() { return "Employee{" + "id=" + id + ", lastname='" + lastname + '\'' + ", email='" + email + '\'' + ", gander='" + gander + '\'' + '}'; } }

EmployeeDao.java (interface):

 package com.lcry.mybatis.dao; import com.lcry.mybatis.bean. Employee; public interface EmployeeDao { Employee getEmp(Integer id); void  insertemp(Employee employee); boolean updateemp(Employee employee); Integer deleteemp(Integer id); }

EmployeeMapper.xml (mapping file configuration):

 <? 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 "> <!-- Namespace, which can be customized. If an interface is bound, it must be consistent with the interface name --> <!-- ID is a unique identifier --> <mapper namespace="com.lcry.mybatis.dao.EmployeeDao"> <select id="getEmp" resultType="com.lcry.mybatis.bean.Employee"> select * from tbl_employee where id = #{id} </select> <insert id="insertemp"  useGeneratedKeys="true" keyProperty="id"> insert into tbl_employee VALUES(null,#{lastname},#{gander},#{email}) </insert> <update id="updateemp"> /*Solve the pit last_name here*/ update tbl_employee set last_name = #{lastname} ,gender=#{gander},email=#{email} where id=#{id} </update> <delete id="deleteemp"> DELETE  FROM tbl_employee WHERE id =#{id} </delete> </mapper>

3) Start testing

MyBatisTest.java (test method):

 package com.lcry.mybatis.test; import com.lcry.mybatis.bean. Employee; import com.lcry.mybatis.dao. EmployeeDao; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session. SqlSession; import org.apache.ibatis.session. SqlSessionFactory; import org.apache.ibatis.session. SqlSessionFactoryBuilder; import org.junit. Test; import java.io.IOException; import java.io.InputStream; public class MyBatisTest { //Get configuration and create sqlSessionFactory factory public static SqlSessionFactory getsqlsession() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); return sqlSessionFactory; } @Test public void test01() throws IOException { SqlSession sqlSession = getsqlsession().openSession(); try { //Query Method Employee employee = sqlSession.selectOne("com.lcry.mybatis.dao.EmployeeDao.getEmp", 10); System.out.println(employee); } finally { sqlSession.close(); } } @Test public void test02() throws IOException { SqlSession sqlSession = getsqlsession().openSession(true); try { EmployeeDao employee = sqlSession.getMapper(EmployeeDao.class); //Query Method Employee emp = employee.getEmp(10); System.out.println(emp.getid()); //Insertion method Employee employee1 = new Employee(); employee1.setLastname("lcry"); employee1.setEmail("1@qq.com"); employee1.setGander("1"); employee.insertemp(employee1); System.out.println(employee1.toString()); //Update method boolean b = employee.updateemp(employee1); System.out.println(b + employee1.toString()); //Delete Method Integer rows = employee.deleteemp(13); System.out.println(rows); } finally { sqlSession.close(); } } }

My project structure is as follows:
 Mybatis from beginner to proficient (I)

Supplement a database sql file (tbl_employee. sql):

 SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for tbl_employee -- ---------------------------- DROP TABLE IF EXISTS `tbl_employee`; CREATE TABLE `tbl_employee` ( `id` int(11) NOT NULL AUTO_INCREMENT, `last_name` varchar(255) DEFAULT NULL, `gender` char(1) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=15 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tbl_employee -- ---------------------------- INSERT INTO `tbl_employee` VALUES ('10', 'lcry', '1', '1@qq.com'); INSERT INTO `tbl_employee` VALUES ('11', 'lcry', '1', '1@qq.com'); INSERT INTO `tbl_employee` VALUES ('12', 'lcry', '1', '1@qq.com'); INSERT INTO `tbl_employee` VALUES ('14', 'lcry', '1', '1@qq.com');

The above is a simple addition, deletion, check and change. Go and try it now~~

Article Contents