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="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.zhurouwangzi</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>
    <!--mybatis Edition-->
    <mybatis.version>3.2.7</mybatis.version>
    <!--log4j Edition-->
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- mybatis Core package -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mysql Driving package -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.29</version>
    </dependency>

    <!-- Log file management package -->
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>RELEASE</version>
      <scope>compile</scope>
    </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>
  • 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 log4j.properties 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 log4j.properties configuration file are as follows:
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
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 "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 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" />
            </dataSource>
        </environment>
    </environments>

</configuration>

 

4, Create entity class

 

 

 

package com.zhurouwangzi.entity;

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

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.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 "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 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}
    </select>
</mapper>
  • 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.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.io.InputStream;

public class MybatisTest {

    @Test
    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 = sqlSessionFactoryBuilder.build(inputStream);
        //4.Obtain SqlSession object
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //5.implement sql Sentence
        UserBaseInfo userBaseInfo = sqlSession.selectOne("getUserById", 16);
        System.out.println(userBaseInfo);
        //close resource
        sqlSession.close();
    }
}

The operation results are as follows:

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