Mybatis: how to use mybatis

Keywords: Java Maven Mybatis log4j Apache

1, Create a project (this article takes the project that Idea builds based on Maven as an example)

  • New->Project










  • I choose my local Maven and configuration here




  • Finally, click Finish




2, Add dependency package in configuration file

  • Add package dependency of Mybatis, JDBC driver and log4j log management in pom.xml configuration file
  • The complete code is as follows:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="" xmlns:xsi=""


  <!-- FIXME change it to the project's website -->

    <!--mybatis Edition-->
    <!--log4j Edition-->


    <!-- mybatis Core package -->
    <!-- mysql Driving package -->

    <!-- Log file management package -->
    <!-- log start -->

    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
        <!-- clean lifecycle, see -->
        <!-- default lifecycle, jar packaging: see -->
        <!-- site lifecycle, see -->
  • After downloading the dependency package, we can see:




  • Add a resource folder under src and right-click Mark Directory As Resources Root



  • Create SqlMapConfig.xml as the global configuration file of Mybatis in src/resource folder
  • After src/resource, create a file to configure the log file
  • Create another sqlmap folder in src/resource to store the mapping files of Mybatis
  • The created project structure is as follows:




3, Set Mybatis related profile

  • The contents of configuration file are as follows:
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
  • The content of SqlMapConfig.xml configuration file is as follows:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-// Config 3.0//EN"
    <!-- and spring After integration environments Configuration will be abolished-->
    <environments default="development">
        <environment id="development">
            <!-- Use jdbc transaction management-->
            <transactionManager type="JDBC" />
            <!-- Database connection pool-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/web_test3?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="root" />



4, Create entity class




package com.zhurouwangzi.entity;

public class UserBaseInfo {
    private int id;
    private String username;

    public String toString(){
        return "User [id=" + id + ", username=" + username+ "]";

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public String getUsername() {
        return username;

    public void setUsername(String username) {
        this.username = username;
  • Add user.xml as the mapping file of UserBaseInfo in src/resource/sqlmap folder




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"
<!-- namespace Is namespace, role sql The isolation of statements plays an important role later
#{}The function is a placeholder, equivalent to jdbc "?"
parameterType: Parameter type of query
resultType: Data type of query result, if pojo Full path should be given.
<mapper namespace="test">
    <select id="getUserById" parameterType="int" resultType="com.zhurouwangzi.entity.UserBaseInfo">
        select * from user_baseinfo where id = #{id}
  • Add < mappers > configuration in SqlMapConfig.xml configuration file:


5, Test with test method area

  • The code is as follows:
package com.zhurouwangzi.service;

import com.zhurouwangzi.entity.UserBaseInfo;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;


public class MybatisTest {

    public void test() throws Exception{
        //1.Create a SqlSessionFactoryBuilder object
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //2.Load profile
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //3.Establish SqlSessionFactory Factory object
        SqlSessionFactory sqlSessionFactory =;
        //4.Obtain SqlSession object
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //5.implement sql Sentence
        UserBaseInfo userBaseInfo = sqlSession.selectOne("getUserById", 16);
        //close resource

The operation results are as follows:

Posted by piyushsharmajec on Fri, 03 Apr 2020 18:46:29 -0700