1. Introduction of MyBatis

In 2001, Clinton Begin launched an open source project called iBATIS, which initially focused on cryptographic software and later evolved into a Java-based persistence layer framework.

In 2004, Clinton donated iBATIS ‘name and source code to the Apache Software Foundation.

In 2010, the core development team decided to leave the Apache Software Foundation and rename iBATIS to MyBatis.

MyBatis is an excellent persistence layer framework that supports custom SQL queries, stored procedures, and advanced mappings, eliminating almost all manual setting of JDBC code and parameters, as well as retrieval of result sets. MyBatis can be configured and mapped using XML or annotations. MyBatis maps parameters to the configured SQL to form the final EXECUTED SQL statement, and finally maps the results of SQL execution to Java objects to return.

Unlike other ORM (Object relational Mapping) frameworks, MyBatis does not associate Java objects with database tables. Instead, MyBatis associates Java methods with SQL statements.

Note: the above content can be understood, because according to my style, especially do not like pure theory pure text things, read my previous blog readers may have this awareness, I prefer specific code actual combat, such as how to use a new technology, a piece of code is to solve what problems……

2. Create a Maven project

For more on Maven, see my previous blog Getting Started with Spring: Managing Spring Projects with Maven.

I’ve always thought that the best way to understand a technology is through a concrete example, like Hello World, haha.

Therefore, first we need to create a New Maven project. The method of creating a Maven project using IDEA is as follows:

The structure of the newly created Maven project looks like this:

The content of the default generated POM.xml file looks like this:

<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zwwhnly</groupId>
    <artifactId>mybatis-action</artifactId>
    <version>1.0 the SNAPSHOT</version>
    
</project>
Copy the code

First, we set the source code encoding to UTF-8:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
Copy the code

Next, set the JDK version to compile the source code. Here we use 1.6 for the time being, you can change it according to your actual needs, such as 1.8:

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
    </plugins>
</build>
Copy the code

Then, add the important MyBatis dependency coordinates and mysql driver dependency coordinates:

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.3.0</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>
    
</dependencies>
Copy the code

Finally, add the dependency coordinates of Log4j and JUnit used. The final pom. XML file contents are as follows:

<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zwwhnly</groupId>
    <artifactId>mybatis-action</artifactId>
    <version>1.0 the SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
Copy the code

In IDEA, if there is no special configuration and the POM file is modified, you need to manually import it. Otherwise, the following situation will occur:

How do I import it manually? Click “Import Changes” in the lower right corner of IDEA.

At this point, the Maven project is created.

3. Simple example

3.1 Data Preparation

Create database mybatis_action_db by executing the following statement:

CREATE DATABASE mybatis_action_db DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
Copy the code

Create table country and add some data:

use mybatis_action_db; CREATE TABLE country ( id INT NOT NULL AUTO_INCREMENT, countryname VARCHAR(255) NULL, countrycode VARCHAR(255) NULL, PRIMARY KEY (id) ); INSERT the country (countryname, countrycode) VALUES (' China 'and' CN '), (' US ', 'US'), (' Russia 'and' RU), (' British ', 'GB), (' France', 'FR);Copy the code

3.2 configure MyBatis

Mybatis -config. XML file (SRC /main/resources)

Then enter the following:

<? The 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> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> <package name="com.zwwhnly.mybatisaction.model"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"> <property name="" value=""/> </transactionManager> <dataSource type="UNPOOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis_action_db"/> <property name="username" value="root"/> <property name="password" value=""/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/zwwhnly/mybatisaction/mapper/CountryMapper.xml"/> </mappers> </configuration>Copy the code

Simple configuration explanation:

  • <settings>The logImpl property configuration in the node specifies the use of LOG4J to output logs.
  • <typeAliases>Elements below configured with a package name, usually determine a class need to use the fully qualified name of a class, such as com. Zwwhnly. Mybatisaction. Model. The Country. In MyBatis need frequent use fully qualified name of a class, for the convenience of use, we configure the com. Zwwhnly. Mybatisaction. Model bag, after such a configuration, at the time of using class don’t need to write a part of the package name, using only the Country.
  • <environments>The environment configuration mainly configures the database connection, for example, here we use the mybatis_action_DB database in the local MySql, the user name is root, there is no password (you can modify the database and user name and password according to their own actual situation).
  • <mappers>Countrymapper.xml, which is a MyBatis Sql statement and mapping configuration file.

3.3 Create entity classes and mapper.xml files

Under the SRC/main/Java package: new com. Zwwhnly. Mybatisaction, then under this package to create package: model.

SQL > alter table country create entity class country;

package com.zwwhnly.mybatisaction.model;

public class Country {
    private Integer id;

    private String countryname;

    private String countrycode;

    // Press Alt+Insert shortcut keys to generate get and set methods
}
Copy the code

In SRC/main/resources create a directory under the com/zwwhnly/simple/mapper directory, and then in that directory to create CountryMapper. XML files, in order to follow-up more quickly create mapper. The XML file, We can refer to the method of adding the mybatis-config.xml template above, which is not described here.

The final countrymapper.xml file reads as follows:

<? The 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="com.zwwhnly.mybatisaction.mapper.CountryMapper"> <select id="selectAll" resultType="Country"> SELECT id,countryname,countrycode from country </select> </mapper>Copy the code

Simple configuration explanation:

  • Mapper: The root element of XML. The namespace attribute defines the namespace of the current XML.
  • Select: A select query that we define.
  • Id attribute: Defines the unique ID of the current Select query.
  • ResultType: Defines the current query returns a value type, here is refers to the entity class Country, the package name mentioned in the previous configuration is mainly used in here, if there is no set package name, here requires written resultType = “com. Zwwhnly. Mybatisaction. Model. The Country”.
  • SELECT id, countryname, countrycode from country: query Sql statements.

3.4 Configuring Log4j to see how MyBatis operates the database

Create a new log4j.properties configuration file under SRC /main/resources and enter the following content:

log4j.rootLogger=ERROR, stdout
log4j.logger.com.zwwhnly.mybatisaction.mapper=TRACE
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n 
Copy the code

3.5 Writing Test code

Under the SRC/test/Java package creation: com. Zwwhnly. Mybatisaction. Mapper, and then create a test class CountryMapperTest class, the code is as follows:

package com.zwwhnly.mybatisaction.mapper;

import com.zwwhnly.mybatisaction.mapper.model.Country;
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.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class CountryMapperTest {
    private static SqlSessionFactory sqlSessionFactory;

    @BeforeClass
    public static void init(a) {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch(IOException e) { e.printStackTrace(); }}@Test
    public void testSelectAll(a) {
        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
            List<Country> countryList = sqlSession.selectList("selectAll");
            printCountryList(countryList);
        } finally{ sqlSession.close(); }}private void printCountryList(List<Country> countryList) {
        for (Country country : countryList) {
            System.out.printf("%-4d%4s%4s\n", country.getId(), country.getCountryname(), country.getCountrycode()); }}}Copy the code

Run the test code and output the following log:

DEBUG [main] – ==> Preparing: SELECT id,countryname,countrycode from country

DEBUG [main] – ==> Parameters:

TRACE [main] – <== Columns: id, countryname, countrycode

TRACE [main] – <== Row: 1, CN

TRACE [main] – <== Row: 2, 美国, US

TRACE [main] – <== Row: 3, RU

TRACE [main] – <== Row: 4, GB

TRACE [main] – <== Row: 5, FR

DEBUG [main] – <== Total: 5

1 China CN

2 the del.icio.us

3 Russia RU

4 the GB

Five French FR

4. Source code and reference

Source code address: github.com/zwwhnly/myb… Welcome to download.

MyBatis from Entry to Mastery by Liu Zenghui

Create XML files in IntelliJ IDEA