Idea creates a simple MyBatis project

Keywords: IntelliJ IDEA Maven Mybatis

catalogue

Article catalog

preface

1, Create Maven project

2, POM configuration

1. Configure JDK version and encoding method

2. Set resource file path

  3. Add dependency

4. All of POM documents

3, Initialization data  

4, Configure mybatis-config.xml

5, Configure config.properties

6, Configure log4j.properties

7, Create the entity class and the corresponding Mapper.xml

6, Testing

summary

preface

A good memory is better than a bad pen

Project directory  

 

 

1, Create Maven project

1. Select File - > New - > project from the menu

2. Select Maven and click Next

3. Enter GroupId and ArtifactId and click Next

GroupId is com.fang.mybatis, and ArtifactId is helloMybatis

  4. Click Finish

2, POM configuration

1. Configure JDK version and encoding method

pom.xml is configured as follows

<plugins>
	<plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-compiler-plugin</artifactId>
		<version>2.3.2</version>
		<configuration>
			<source>1.8</source>
			<target>1.8</target>
			<encoding>UTF-8</encoding>
		</configuration>
	</plugin>
</plugins>

After setting, the encoding method is UTF-8 and the JDK version is 1.8  

2. Set resource file path

Maven   By default, only resource files under resource will be packaged. If our file is not placed in resource, Maven needs to be informed through configuration.

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
    </resource>
</resources>

  3. Add dependency

<!--mybatis-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.5</version>
</dependency>

<!--database mysql drive-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.45</version>
</dependency>

<!-- realization slf4j Interface and integration -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.10.0</version>
</dependency>

<!--junit test-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

Logs are added so that sql statements can be output during testing.

4. All of POM documents

<?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.fang.mybatis</groupId>
    <artifactId>helloMybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
    </plugins>

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

<dependencies>
    <!--mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>

    <!--database mysql drive-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.45</version>
    </dependency>

    <!-- realization slf4j Interface and integration -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.25</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.25</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.10.0</version>
    </dependency>

    <!--junit test-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>
</project>

3, Initialization data  

1. Database creation script

CREATE DATABASE IF NOT EXISTS `mybatis` DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

2. Create student table

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `student_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'number',
  `name` VARCHAR(20) DEFAULT NULL COMMENT 'full name',
  `phone` VARCHAR(20) DEFAULT NULL COMMENT 'Telephone',
  `email` VARCHAR(50) DEFAULT NULL COMMENT 'mailbox',
  `sex` TINYINT(4) DEFAULT NULL COMMENT 'Gender',
  `locked` TINYINT(4) DEFAULT NULL COMMENT 'state(0:normal,1:locking)',
  `gmt_created` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT 'Time stored in database',
  `gmt_modified` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Time of modification',
  PRIMARY KEY (`student_id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='Student list';

  3. Insert test data

INSERT INTO `student`(`name`, phone, email, sex, locked)
VALUES
('Xiao Ming', 13821378270, 'xiaoming@mybatis.cn', 1, 0),
('Xiao Li', 13821378271,  'xiaoli@mybatis.cn', 0, 0),
('Xiao Gang', 13821378272, 'xiaogang@mybatis.cn', 1, 0),
('floret', 13821378273, 'xiaohua@mybatis.cn', 0, 0),
('cockroach', 13821378274, 'xiaoqiang@mybatis.cn', 1, 0),
('Xiao Hong', 13821378275, 'xiaohong@mybatis.cn', 0, 0);

4, Configure mybatis-config.xml

<?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>
    <properties resource="config.properties"/>
    <settings>
        <setting name="logImpl" value="LOG4J" />
    </settings>
    <typeAliases>
        <package name="com.fang.mybatis.entity"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">

            <transactionManager type="JDBC">
                <property name="" value=""/>
            </transactionManager>
            <dataSource type="POOLED">
               <!-- <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>-->

                <property name="driver" value="${database.driver}"/>
                <property name="url" value="${database.url}"/>
                <property name="username" value="${database.username}"/>
                <property name="password" value="${database.password}"/>
            </dataSource>
        </environment>
    </environments>



    <mappers>
        <package name="com.fang.mybatis.mapper"/>
    </mappers>


</configuration>

1. Configure properties and point to the configuration file, which contains data source information
2. Configure settings. In this project, it is mainly used to configure log output. Log4j is configured in pom.xml, so the log implementation value here is log4j.
3. Configure typeAliases. Type aliases set a short name for Java types. It is only related to XML configuration, and its significance is only to reduce the redundancy of class fully qualified names.
In mybatis, Student can be used wherever com.fang.mybatis.entity.Student is used. However, generally speaking, there are many entities, so this configuration is too cumbersome. Mybatis supports specifying the package name and uses the first lowercase class qualified name of the class as the alias.
4. Configure environments, corresponding to database related attributes. We can configure multiple environments, but only one can be selected for each SqlSessionFactory instance. In this project, we only need to configure one. The database we just created is mybatis.
5. Configure mappers. Similarly, it can be configured individually or identified by scanning packets.? This configuration will scan all. xml files in the specified package, which contain mybatis SQL statements and mapping configuration files. It will be created later.

5, Configure config.properties

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/mybatis
database.username=root
database.password=123456

6, Configure log4j.properties

log4j.rootLogger=INFO,Console
log4j.additivity.org.apache=true

log4j.logger.com.fang.mybatis.mapper=TRACE

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.org.apache=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

7, Create the entity class and the corresponding Mapper.xml

1. Create entity class

For the entity class, the attributes need to correspond to the fields in the database table one by one, and have corresponding getter, setter and toString methods

package com.fang.mybatis.entity;

import java.util.Date;

public class Student {
    private Integer studentId;

    private String name;

    private String phone;

    private String email;

    private Byte sex;

    private Byte locked;

    private Date gmtCreated;

    private Date gmtModified;
    /**
     * The following parts are setter s and getter s, which are omitted
     */
    public Integer getStudentId() {
        return studentId;
    }

    public void setStudentId(Integer studentId) {
        this.studentId = studentId;
    }

    public String getName() {
        return name;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Byte getSex() {
        return sex;
    }

    public void setSex(Byte sex) {
        this.sex = sex;
    }

    public Byte getLocked() {
        return locked;
    }

    public void setLocked(Byte locked) {
        this.locked = locked;
    }

    public Date getGmtCreated() {
        return gmtCreated;
    }

    public void setGmtCreated(Date gmtCreated) {
        this.gmtCreated = gmtCreated;
    }

    public Date getGmtModified() {
        return gmtModified;
    }

    public void setGmtModified(Date gmtModified) {
        this.gmtModified = gmtModified;
    }

    @Override
    public String toString() {
        return "Student{" +
                "studentId=" + studentId +
                ", name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                ", email='" + email + '\'' +
                ", sex=" + sex +
                ", locked=" + locked +
                ", gmtCreated=" + gmtCreated +
                ", gmtModified=" + gmtModified +
                '}';
    }
}

2. Create Mapper interface and Mapper.xml

StudentMapper.java

package com.fang.mybatis.mapper;

import com.fang.mybatis.entity.Student;

import java.util.List;

public interface StudentMapper {

    /**
     *
     * @return
     */
    List<Student> selectAll();
}

 StudentMapper.xml

<?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.fang.mybatis.mapper.StudentMapper">
    <resultMap id="BaseResultMap" type="com.fang.mybatis.entity.Student">
        <id column="student_id" jdbcType="INTEGER" property="studentId" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="phone" jdbcType="VARCHAR" property="phone" />
        <result column="email" jdbcType="VARCHAR" property="email" />
        <result column="sex" jdbcType="TINYINT" property="sex" />
        <result column="locked" jdbcType="TINYINT" property="locked" />
        <result column="gmt_created" jdbcType="TIMESTAMP" property="gmtCreated" />
        <result column="gmt_modified" jdbcType="TIMESTAMP" property="gmtModified" />
    </resultMap>
    <sql id="Base_Column_List">
    student_id, name, phone, email, sex, locked, gmt_created, gmt_modified
  </sql>
    <select id="selectAll" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from student
    </select>
</mapper>

The result mapping and sql statements are configured, where the id (selectAll) in sql is consistent with the method name in Mapper.

6, Testing

package com.fang.mybatis;

import com.fang.mybatis.entity.Student;
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.Reader;
import java.util.List;


public class StudentMapperTest {
    private static SqlSessionFactory sqlSessionFactory;

    @BeforeClass
    public static void init() throws Exception{
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testSelectList() {
        SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession();

            List<Student> students  = sqlSession.selectList("selectAll");
            for (int i = 0; i < students.size(); i++) {
                System.out.println(students.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}

Execution results:

 

summary

1. Read mybatis-config.xml through the Resources tool class and store it in the Reader;
2.SqlSessionFactoryBuilder creates a SqlSessionFactory object using the reader obtained in the previous step;
3. Obtain SqlSession through sqlSessionFactory object;
4. The sqlsession object finds the corresponding "selectAll" statement through the selectList method and executes the SQL query.
5. The bottom layer obtains the ResultSet after querying through JDBC. For each record, it is mapped to Student according to the mapping result of resultMap and returns List.
6. Finally, remember to close SqlSession.

Posted by Illusion on Sat, 25 Sep 2021 10:45:55 -0700