MyBatis is a Java persistence framework that associates objects with stored procedures or SQL statements through XML descriptors or annotations.
MyBatis is a free software distributed under Apache license 2.0 and is a branch version of iBATIS 3.0. Its maintenance team also includes iBATIS startup members.
Unlike other object-relational mapping frameworks, MyBatis does not associate Java objects with database tables, but rather Java methods with SQL statements. MyBatis allows users to take full advantage of various database functions, such as stored procedures, views, various complex queries, and the proprietary features of a database. If you want to operate on legacy databases, irregular databases, or have complete control over SQL execution, MyBatis is a good choice.
Compared with JDBC, MyBatis simplifies the relevant code: SQL statements can be executed in one line of code. MyBatis provides a mapping engine that declaratively maps the execution results of SQL statements with the object tree. SQL statements can be generated dynamically by using a built-in XML-like expression language, or using Apache Velocity-integrated plug-ins.
MyBatis integrates with Spring Framework and Google Guice, which saves developers from dependency issues.
MyBatis supports declarative data caching. When an SQL statement is marked as "cacheable", all data obtained from the database when it is first executed will be stored in a cache. When this statement is executed in the future, the result will be read from the cache instead of hitting the database again. MyBatis provides a Java HashMap-based cache implementation by default, as well as a default connector for connections with OSCache, Ehcache, Hazelcast, and Memcached. MyBatis also provides API for other cache implementations.
Important points
After learning during this period, the main process for Mybatis cannot be the following steps
1. Get the SessionFactory from the XML configuration file, and then generate the corresponding Session from the SessionFactory.
2. Use the Session object to complete the corresponding CRUD operations (addition, deletion, modification and query) and corresponding transaction control on the business data.
3. Close the corresponding session after use to avoid excessive resource consumption
4. Use the corresponding Mapper xml file to configure the corresponding map operation between the JavaBean of the business entity and the database table.
Pre-war preparations:
1. Development environment Eclipse JavaEE IDE, JDK 1.6, database mysql 5.5
2. Download the corresponding Jar package for later use
Mybatis-3.2.3.zip After decompression, take out mybatis-3.2.3.jar, => Download address: http://code.google.com/p/mybatis/ (Mybatis core package)
mybatis-generator-core-1.3.1.jar => Download address: http://code.google.com/p/mybatis/wiki/Generator (Mybatis automatically generates configuration file package)
mysql-connector-java-5.1.26-bin.jar => Download address: http://dev.mysql.com/downloads/connector/j/ (Mysql's jdbc driver package)
Construction steps
Next, you can create a Java Project project called MybatisDemo under Eclipse, and create the corresponding package structure and folder structure as shown in the figure below, where config and mapper are folders respectively.
The corresponding demo runner program and Javabean objects are stored under the package david.mybatis.demo and the package david.mybatis.model, and the third-party jar packages just downloaded are stored in the lib folder.
After creating the following directory, we can add the corresponding Jar package as shown in the figure below
After completion, execute the following SQL to establish the table structure required for DEMO, including 3 tables, Visitor (visitor table), Website (website table), and Channel (channel table)
/*Create Visitor*/CREATE TABLE Visitor( Id INT(11) NOT NULL AUTO_INCREMENT, Name VARCHAR(1000) NOT NULL, Email VARCHAR(1000) NOT NULL, Status INT NOT NULL DEFAULT 1, CreateTime DateTime, PRIMARY KEY(Id))/*Create website table*/CREATE TABLE Website( Id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(1000) NOT NULL, VisitorId INT REFERENCES Visitor(Id), Status INT NOT NULL DEFAULT 1, CreateTime DateTime)/*Create channel table*/CREATE TABLE Channel( Id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(1000) NOT NULL, WebsiteId INT REFERENCES Website(Id), Status INT NOT NULL DEFAULT 1, CreateTime DateTime)
After all this is done, we will start to do it~
As mentioned at the beginning, all Mybatis configurations originate from an XML configuration file. We need to create a new configuration file named mybatis_demo_config.xml in the config folder. This thing is one of the core operations we need to operate later.
When configuring this file, you must pay attention to the elements in the <configuration> node that have hierarchical order requirements and cannot be changed at will. Otherwise, an exception will occur when loading the xml configuration file, resulting in unsuccessful subsequent operations.
For specific node descriptions, you can check http://mybatis.github.io/mybatis-3/zh/configuration.html#. Here we only talk about the more commonly used nodes, typeAliases, environments, mappers.
1. typeAliases => Alias node. You can set the properties of this node so that this alias is used instead of a fully qualified name in the configuration file.
For example <typeAlias type="david.mybatis.model.Visitor" alias="Visitor" />
2. environments => environment node, configuring data connection related information
3. mappers => Configure SQL mapping statements.
The simplest configuration is as follows:
<?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> <typeAliases> <typeAlias type="david.mybatis.model.Visitor" alias="Visitor" /> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <!-- ?useUnicode=true&characterEncoding=utf8 To support Chinese insertion--> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis_db?useUnicode=true&characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/VisitorMapper.xml" /> </mappers></configuration>
Create a new class called MyBatisUtils under the package david.mybatis.demo, which stores the methods to obtain SqlSession and close SqlSession, which are extracted to facilitate multiple reuse.
package david.mybatis.demo;import java.io.InputStream;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 david.mybatis.model.CRUD_Enum;public class MybatisUtils { private static final String CONFIG_PATH = "config/mybatis_demo_config.xml"; /* * Get database access link*/ public static SqlSession getSqlSession() { SqlSession session = null; try { InputStream stream = Resources.getResourceAsStream(CONFIG_PATH); // The corresponding database environment can be read according to the corresponding environment configured// SqlSessionFactory factory = new SqlSessionFactoryBuilder().build( // stream, "development"); SqlSessionFactory factory = new SqlSessionFactoryBuilder() .build(stream); session = factory.openSession(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return session; } /* * Get database access link */ public static void closeSession(SqlSession session) { session.close(); } /* * Return operation record message*/ public static void showMessages(CRUD_Enum type, int count) { switch (type) { case Add: System.out.println("Added" + count + " record. "); break; case Delete: System.out.println("Deleted" + count + "Records."); break; case Update: System.out.println("Updated" + count + "Records."); break; case Query: System.out.println("Matched" + count + "Records."); break; case List: System.out.println("Total" + count + "Records."); break; default: break; } }}Create a new class named Visitor under the package david.mybatis.model to use it as the corresponding OR Mapping.
package david.mybatis.model;import java.text.SimpleDateFormat;import java.util.Date;public class Visitor { private int id; private String name; private String email; private int status; private Date createTime; public Visitor() { // TODO Auto-generated constructor stub createTime = new Date(); } public Visitor(String name, String email) { this.name = name; this.email = email; this.status = 1; this.createTime = new Date(); } public int getId() { return id; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setEmail(String email) { this.email = email; } public String getEmail() { return email; } public Date getCreateTime() { return createTime; } @Override public String toString() { // TODO Auto-generated method stub return String.format("{Id: %d, Name: %s, CreateTime: %s}", id, name, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTime)); }}Create a new VisitorMapper.xml under the package david.mybatis.demo to map the corresponding SQL statement.
Here you should note that namespace=>david.mybatis.demo.IVisitorOperation must be associated with the actual file name below the corresponding package. Otherwise, the corresponding mapping file cannot be loaded successfully.
<mapper namespace="david.mybatis.demo.IVisitorOperation"> <select id="basicQuery" parameterType="int" resultType="Visitor"> select * from visitor where id=#{id} and Status>0 order by Id </select></mapper> Next run the following program
public static void testBasicQuery(int id) { SqlSession session = MybatisUtils.getSqlSession(); try { Visitor visitor = (Visitor) session.selectOne("david.mybatis.demo.IVisitorOperation.basicQuery", id); MybatisUtils.closeSession(session); System.out.println(visitor); } catch (Exception e) { // TODO: handle exception } } The simplest execution result is out
This is the HelloWord of the Mybatis series~