Three implementation methods of mybatis: pure xml configuration

**

The implementation of mybatis: pure xml configuration

**

  • First,

First, add mybatis related dependency

    <dependency>
	    <groupId>org.mybatis</groupId>
	    <artifactId>mybatis</artifactId>
	    <version>3.5.1</version>
    </dependency>
    <dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.21</version>  
    </dependency>
  • Two
    Create a new mybatis.xml file. The header and other information of the file can be obtained from the official website cv of mybatis
<?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">

<!--
    The configuration file contains a configuration node
        The configuration information is environment and mapping
        In the environment, there is datasource, which contains four familiar strings connecting to the database
-->
<configuration>
    <! -- import properties file -- >
    <properties resource="db.properties"/>

    <! -- add log -- >
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
            <! -- the value is the value of k in the imported properties file, so the variable name cannot be changed
            Note that the $sign is used here to distinguish the "×"
		-->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${root}"/>
                <property name="password" value="${pass}"/>
            </dataSource>
        </environment>
    </environments>
    
    <! -- mapper of configuration file. The specific sql statement is in the following configuration file. Each configuration file represents
    Operations in different tables -- >
    <mappers>
        <mapper resource="OrderMapper.xml"/>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>
  • Three
    Suppose that there is a users table in the database, first create a new users class. Note that the properties in the class are consistent with the fields in the database in terms of type and name
package com.qianfeng.pojo;

public class Users {

    private int uid;
    private String name;
    private String pass;

    public Users() {
    }

    public Users(int uid, String name, String pass, String phone) {
        this.uid = uid;
        this.name = name;
        this.pass = pass;
        this.phone = phone;
    }

    @Override

    public String toString() {
        return "Users{" +
                "uid=" + uid +
                ", name='" + name + '\'' +
                ", pass='" + pass + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getName() {
        return name;
    }

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

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    public String getPhone() {
        return phone;
    }

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

    private String phone;

}

In this way, we can introduce a dependency lombok. For this dependency, we can use annotation to solve the manual implementation of constructor, getset, and tostring in the class, which is convenient for maintenance and modification. When we add a dependency, we first add it

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.8</version>
</dependency>

Then search for lombok in the plug-in to download and install it, and restart the idea. After the installation is successful, the code of users class can be abbreviated as follows

package com.qianfeng.pojo;

import lombok.*;

@ToString
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class Users {

    private int uid;
    private String name;
    private String pass;
    
}

After introducing a gadget, get back to the point

  • Four
    Add the UserMapper.xml file, which is the file mapped in mybatis.xml file. Similarly, the related information of the header can be cv to
<?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">

<!--
    Each mapper file will have its own mapped namespace,
    Each method corresponds to its own sql statement, and each sql statement corresponds to an id
    All namespace.id s in the entire project must be unique
-->

<mapper namespace="com.qianfeng.pojo.UserMapper">
    <select id="getUserByUid" resultType="com.qianfeng.pojo.User">
        select * from users WHERE uid=#{uid}
    </select>

</mapper>

Some points to be explained are
First: the value in namespace must be unique in the whole current file, usually written as the name of the related class
Second: the id value must be unique in the whole namespace. It is not required in different namespase s. It is usually the name of the operation

-5, Testing

  • 1. First, create the SqlSessionFactory object, and load the mybatis.xml file as a stream
SqlSessionFactory    sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));`
  • 2. Create a SqlSession object to call the implementation of specific methods
session = sf.openSession();

The specific implementation is as follows:

package com.qianfeng.testpojo;

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.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

/**
 * Created by Administrator on 2020/3/11.
 */
public class testPojo {
    private SqlSessionFactory sf = null;
    private SqlSession session = null;

    @Before
    public void before(){
        try {
            sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));

            session = sf.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @After
    public void after() {
        if (session != null) {
            session.close();
            session = null;
        }
    }

    @Test
    public void test1(){
        Object selectOne = session.selectOne("com.qianfeng.pojo.OrdersMapper.getOrderByOid", "ef12c8a462e011eaa1757c3aacb2763b");
        System.out.println(selectOne);
    }
}

Published 4 original articles, won praise 1, visited 53
Private letter follow

Tags: Mybatis xml Session Apache

Posted on Sun, 15 Mar 2020 04:11:52 -0700 by brownca