Building and testing of mybatis environment


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.


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

    <!--  JUnit unit test -- >
    <!--  MySQL driver -- >
    <!-- mybatis -->

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 "-// Config 3.0//EN"
<!--  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"/>
    <!--  2. Import mapper configuration file. If there are multiple mapper files, you can import them through multiple mapper tags -- >
        <mapper resource="/mapper.xml"/>

Add the following to the mapper.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-// Mapper 3.0//EN"

    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

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) { = id;
    public String getName() {
        return name;
    public void setName(String 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;
    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
public void findAll() throws IOException {
    //1. Read the core configuration file of mybatis (mybatis config. XML)
    InputStream in = Resources
    //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
    //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