Building and testing of mybatis environment

Time:2021-6-8

About mybatis

1. What is mybatis

Mybatis is an excellent persistence layer framework, which supports customized SQL, stored procedures and advanced mapping. Mybatis avoids almost all JDBC code and manual setting of parameters and obtaining result sets. Developers only need to pay attention to SQL itself, and do not need to spend energy to deal with JDBC complex process code, such as registering driver, creating connection, creating statement, manually setting parameters, result set retrieval and so on.

preparation

Create DB_ Mybatis library, EMP table, insert some records

--1. Create database_ Mybatis database
create database if not exists db_mybatis charset utf8;
use db_ mybatis; --  Select dB_ Mybatis database
--2. Delete EMP table (if any)
drop table if exists emp;
--3. In DB_ Creating EMP table in mybatis Library
create table emp(
    id int primary key auto_increment,
    name varchar(50),
    job varchar(50),
    salary double
);
--4. Insert several records into the EMP table
Insert into EMP values (null, 'Li Si', 'programmer', 3300);
Insert into EMP values (null, 'Wang Wu', 'programmer', 2800);
Insert into EMP values (null, 'little flower', 'programmer encouragement', 2700);
Insert into EMP values (null, 'Zhao Liu', 'department director', 4200);
Insert into EMP values (null, 'Xiaoming', 'programmer', 3000);

1. Create a project

1.1 create a maven web project

Building and testing of mybatis environment
Building and testing of mybatis environment

1.2 generate web.xml

Building and testing of mybatis environment

1.3 create configuration file

Under Src / main / resources:

Create mybatis / mybatis-config.xml
Create mapper / mapper.xml

Building and testing of mybatis environment

1.4 project creation and structure display

Building and testing of mybatis environment

2. Add dependencies and configuration files

2.1 add dependency to pom.xml file

<dependencies>
    <!--  JUnit unit test -- >
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
    </dependency>
    <!--  MySQL driver -- >
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.32</version>
    </dependency>
    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.2.8</version>
    </dependency>
</dependencies>

Building and testing of mybatis environment

2.2 add configuration file content

Add the following contents to 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">
    
<!--  Mybatis global profile -- >
<configuration >
    <!--  1. Configuration environment. Multiple environments can be configured (such as development and test) - >
    <environments default="develop">
        <environment id="develop">
            
            <!--  1.1. Configuration transaction management mode: JDBC / managed
            JDBC: leaving transactions to JDBC (recommended)
            Managed: manage your own business
              -->
            <transactionManager type="JDBC"></transactionManager>
            
            <!--  1.2. Configure the data source, that is, the connection pool JNDI / pooled / unpooled
                JNDI: out of date
                Pool: using connection pool (recommended)
                Unpooled: no connection pooling
             -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/db_mybatis?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    
    <!--  2. Import mapper configuration file. If there are multiple mapper files, you can import them through multiple mapper tags -- >
    <mappers>
        <mapper resource="/mapper.xml"/>
    </mappers>
</configuration>

Add the following to the mapper.xml file:

<?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">

<!-- 
    The namespace values of different mapper files should be unique
    Locate which SQL statement to execute through [namespace + ID] in the program
 -->
<mapper namespace="EmpMapper">
    <!--  Declare the SQL to be executed through the tags of select, insert, update and delete -- >
    <select id="findAll" resultType="com.yanan.pojo.User">
        select * from emp
    </select>
</mapper>

3. Code implementation

3.1 write user entity class

Note: the attribute name in the entity class must be consistent with the field name in the database, otherwise it cannot be encapsulated.
Create a user entity class, and provide get, set, and override tostring() methods

package com.yanan.pojo;

/**
 *Entity class
 *@ author Moke
 *
 */
public class User {
    //1. Declare the properties in the entity class
    private Integer id;
    private String name;
    private String job;
    private Double salary;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public Double getSalary() {
        return salary;
    }
    public void setSalary(Double salary) {
        this.salary = salary;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", job=" + job + ", salary=" + salary + "]";
    }
}

3.2 writing implementation class (mapperdaotest)

Write the findall() method:

/**
 *Query all user information and return a list < user > function
 * @throws IOException
 */
@Test
public void findAll() throws IOException {
    //1. Read the core configuration file of mybatis (mybatis config. XML)
    InputStream in = Resources
            .getResourceAsStream("mybatis-config.xml");
    //2. Get a sqlsessionfactory factory object through configuration information
    SqlSessionFactory fac = 
            new SqlSessionFactoryBuilder().build( in );
    //3. Get a sqlsession object through the factory
    SqlSession session = fac.openSession();
    //4. Find the SQL statement to be executed through the namespace + ID and execute the SQL statement
    List<User> list = session
            .selectList("EmpMapper.findAll");
    //5. Output results
    for(User e : list) {
        System.out.println( e );
    }
}

3.3 result display

Execute the findall method, and the output result is:
Building and testing of mybatis environment