MyBatis Quick Start

Posted by tmayder on Sat, 18 May 2019 12:48:22 +0200


What is Mybatis?

MyBatis is an excellent persistence layer "semi-automated" ORM (Object Relational Mapping) framework, which encapsulates the code of JDBC operation database process internally, so that developers only need to pay attention to the SQL statement itself, without wasting any more energy to deal with such issues as loading database driver, creating Connection database Connection, creating Statement, setting parameters manually, knotting. Comparing with traditional JDBC, nearly 95% of the code is omitted in the complex process of retrieving fruit sets and closing connections.

Mybatis can configure and map native information through simple xml or annotations, mapping interfaces and java POJO (common java objects) into records in the database.

Persistence Layer: Transfer data from memory to disk to achieve persistent storage of data.


Create a maven project

Create a maven project The project name is mybatisDemo

The newly created project structure Final project structure

pom.xml file

Add in the pom.xml file mybatis ,mysql-connector-java ,log4j After adding jar s, don't forget to click Import Changes in the lower right corner

In the pom.xml file below, except for the three jar s I added, all the other code is automatically generated.

<?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.CD4356</groupId>
  <artifactId>mybatisDemo</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>mybatisDemo</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis/3.1.1 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.1.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.46 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.29</version>
    </dependency>
    <!--https://mvnrepository.com/artifact/log4j/log4j/1.2.17-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>


Database Environment
// Create mybatis database
create database mybatis;

use mybatis
// Create teacher tables
create table teacher(
	id int (11) not null  auto_increment,
	name varchar (96) not null,
	primary key(id)
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 

INSERT INTO teacher VALUES(NULL,'zhang');
INSERT INTO teacher VALUES(NULL,'li');

Database table mapping class (entity class)
Create the pojo package under src-main-java-com.Cd4356, and create the mapping class (entity class) of the teacher table in the package.
package com.CD4356.pojo;

public class Teacher {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Teacher [id="+id+", name="+name+"]";
    }
}

Create the resource directory under src-main, then create the mybatis-config.xml configuration file under the resource directory. The problem arises There is no template for the mybatis-config.xml configuration file in idea, nor for the mapper.xml mapping file. We need to build it in Fillates and Code Temp by ourselves, so we can't find the template at the beginning. Documentation


Build the template file of mybatis-config.xml

File Settings Editor File and Code Templates Files + Enable Live Templates Scheme Selection Default

The template content of mybatis-config.xml 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>
    
</configuration>

Build the template file of mybatis-config.xml

According to the method of building the template file of mybatis-config.xml, the template file of mapper.xml is built. The template content of mapper.xml file is as follows:

<?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="">
    
</mapper>

mybatis-config.xml configuration file

Create the resource directory under src - main, and then create the mybatis-config.xml configuration file under the resource directory

The mybatis-config.xml file 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>

    <!--To configure<properties/>Label,Add to jdbc.properties come in,Convenient connection to database-->
    <properties resource="jdbc.properties"/>

    <!--Automatic scanning-->
    <typeAliases>
        <package name="com.CD4356.pojo"/>
    </typeAliases>

    <!-- To configure mybatis Running environment, When mybatis and spring After integration environments Configuration will be abolished -->
    <environments default="development">
        <environment id="development">
            <!-- Use jdbc transaction management,Transaction control by mybatis -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- Configure database connection pool,from mybatis Administration -->
            <!-- mybatis Three types of data sources are provided, namely: POOLED,UNPOOLED,JNDI -->
            	<!-- POOLED Express support JDBC Data Source Connection Pool -->
            	<!-- UNPOOLED Indicates that data source connection pool is not supported -->
            	<!-- JNDI Represents support for external data source connection pools -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- Load Mapping file -->
    <mappers>
        <!-- register Teacher.xml Mapping File-->
        <mapper resource="mapper/Teacher.xml"/>
    </mappers>

</configuration>

jdbc.properties file

Create the jdbc.properties file in the resource directory

The jdbc.properties file is as follows:

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8
jdbc.username = root
jdbc.password = root

xml Mapping File

Create a mapper directory in the resource directory and a Teacher.xml Mapping file in the mapper directory

The Teacher.xml mapping file is as follows:

<?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="mapper">
    <!--increase-->
    <insert id="add" parameterType="Teacher" >
            insert into teacher ( name ) values (#{name})
        </insert>

    <!--change-->
    <update id="update" parameterType="Teacher" >
            update teacher set name=#{name} where id=#{id}
        </update>

    <!--Delete-->
    <delete id="delete" parameterType="Teacher" >
            delete from teacher where id= #{id}
        </delete>

    <!--according to id check-->
    <select id="get" parameterType="_int" resultType="Teacher">
            select * from teacher  where id= #{id}
        </select>

    <!--Check all-->
    <select id="getAll" resultType="Teacher">
            select * from teacher
        </select>

</mapper>

log4j.properties log file

Create log4j.properties file in the resource directory

The log4j.properties log file reads as follows: (The code I found online)

### Set up Logger Output Level and Output Destination ###
log4j.rootLogger=debug,stdout,logfile

### Export log information to console ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout

### Export log information to files: jbit.log ###
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=jbit.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n

###Display the SQL statement section
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

MyBatis programming steps

1. Loading mybatis global configuration file

2. Create SqlSession Factory

3. Create SqlSession through SqlSession Factory

4. Perform database operations through SqlSession

5. Call sqlSession.commit() to commit a transaction

6. Call sqlSession.close() to close the database session

Delete the app class under package com.CD4356 (I don't like to use this class as a Test class) and create a Test test class

package com.CD4356;

import com.CD4356.pojo.Teacher;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Test {

    public static void main(String[] args) throws IOException {

        // Load the mybatis core configuration file (together with the associated mapping file)
        InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml");
        // Create SqlSessionFactory
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        // Get SqlSession from SqlSession Factory
        SqlSession sqlSession=sqlSessionFactory.openSession();

        Teacher teacher=new Teacher();
        // increase
        teacher.setName("wang");
        sqlSession.insert("add",teacher);

        // change
        teacher.setId(3);
        teacher.setName("chen");
        sqlSession.insert("update",teacher);

        // Delete
        teacher.setId(3);
        sqlSession.insert("delete",teacher);

        System.out.println("check");
        getAll(sqlSession);

        sqlSession.commit(); // Submission of affairs
        sqlSession.close(); // Closing session
    }

    private static void getAll(SqlSession sqlSession){
        List<Teacher> ts=sqlSession.selectList("getAll");
        for (Teacher t:ts){
            System.out.print(t.getId()+" , ");
            System.out.println(t.getName());
        }
    }

}




Using IDEA to build SpringBoot project and integrate mybatis to realize simple login function

SSM Integration Project (IDEA+Maven+MySql)

Topics: Mybatis xml Maven log4j