MyBatis's predecessor was iBatis, which was originally an open source project of apache. In 2010, this project was moved from apache software foundation to Google code and was renamed MyBatis. MyBatis is an excellent persistence layer framework that supports plain SQL queries, stored procedures and advanced mapping. MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval of result sets. MyBatis uses simple XML or annotations for configuration and original mapping, mapping interfaces and Java's POJOs (Plan Old Java Objects, ordinary Java objects) into records in the database.
Mybatis' functional architecture is divided into three layers (the picture is borrowed from Baidu Encyclopedia):
1) API interface layer: Provides interface APIs for external use, through which developers manipulate databases. Once the interface layer receives the call request, it will call the data processing layer to complete the 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 based on the request of the call.
3) Basic support layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading and cache processing. These are all common things, extracting them as the most basic components. Provides the most basic support for the upper layer of data processing layer.
Here is a simple MyBatis using DEMO.
Overall structure
POM dependency
Two jar packages need to be referenced, one is mybatis and the other is mysql-connector-java. If it is a maven project, add dependencies in the pom as follows.
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.3</version></dependency><dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version></dependency>
Data preparation
Create point data in MySQL for testing:
CREATE DATABASE mybatis_test;CREATE TABLE user( age INTEGER NOT NULL, name VARCHAR(64) NOT NULL DEFAULT '');insert user values(18,'zhanjindong');insert user values(20,'zhangsan');
Configuration File
Two types of configuration files are required. One is the MyBatis configuration file mybatis-config.xml. In the example, it is a very simple configuration. There are many instructions for the detailed configuration on the Internet.
<?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> <settings> <!-- changes from the defaults for testing --> <setting name="cacheEnabled" value="false" /> <setting name="useGeneratedKeys" value="true" /> <setting name="defaultExecutorType" value="REUSE" /> </settings> <typeAliases> <typeAlias alias="User" type="test.mybatis.User"/> </typeAliases> <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://192.168.71.38:3306/mybatis_test"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mappers/UserMapper.xml" /> </mappers> </configuration>
Another type is the data access interface mapping file: in the example it is UserMapper.xml. This file can be found by src/main/resource or subdirectory mybatis. It is specified by the resource of the mappers/mapper node in mybatis-config.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="test.mybatis.UserMapper"> <!-- Here the namespace must be the path of the UserMapper interface" --> <insert id="insertUser" parameterType="User"> insert into user(name,age) values(#{name},#{age}) <!-- Here, no semicolons can be added at the end of SQL, otherwise an error of "ORA-00911" will be reported--> </insert> <!-- The id here must be the same as the interface method name in the UserMapper interface--> <select id="getUser" resultType="User" parameterType="java.lang.String"> select * from user where name=#{name} </select></mapper> The corresponding mapping file is the UserMapper interface under the namespace test.mybatis, which only defines the interface to access the data table:
package test.mybatis;public interface UserMapper { public void insertUser(User user); public User getUser(String name);} Need a POJO:User.java
package test.mybatis;public class User { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public User(String name, Integer age) { super(); this.name = name; this.age = age; } public User() { super(); }} test
The MyBatis database operation uses a class called SqlSession. This class is generated through SqlSessionFactory. It is generally recommended to maintain a SqlSessionFactory globally.
TestMyBatis.java
package test.mybatis;import java.io.IOException;import java.io.Reader;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class MyBatisUtil { private final static SqlSessionFactory sqlSessionFactory; static { String resource = "mybatis-config.xml"; Reader reader = null; try { reader = Resources.getResourceAsReader(resource); } catch (IOException e) { System.out.println(e.getMessage()); } sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; }}The test code is as follows:
TestMyBatis.java
package test.mybatis;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;public class TestMyBatis { static SqlSessionFactory sqlSessionFactory = null; static { sqlSessionFactory = MyBatisUtil.getSqlSessionFactory(); } public static void main(String[] args) { testAdd(); getUser(); } public static void testAdd() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = new User("lisi", new Integer(25)); userMapper.insertUser(user); sqlSession.commit();// You must submit here, otherwise the data will not enter the database} finally { sqlSession.close(); } } public static void getUser() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.getUser("zhangsan"); System.out.println("name: " + user.getName() + "|age: " + user.getAge()); } finally { sqlSession.close(); } }} Things to note
1. Mybatis will use log4j to record logs, but turning on debug mode seems to have a very strong impact on performance.
2. Mybatis' query cache has a very big impact on performance, and the gap between enabling and not enabling is very big.
Note: The cache line must be added to the mapper file, otherwise it will not take effect.
Sample code download: Code download
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.