SpringBoot-Mybatis Framework--Actual Notes

0-Preface

Mybatis was predecessor to iBatis, an open source project for Apache.

Mybatis is a Hibernate-like ORM persistence framework that supports common SQL queries, stored procedures, and advanced mappings.

Mybatis typically uses simple xml or annotations to configure and map interfaces and POJO objects to records in the database.

Since Mybatis is a simple mapping wrapper based directly on JDBC, all in terms of performance:

JDBC>Mybatis>Hibernate

The overall framework of Mybatis

] (C:Users10224683Documents Notes_Cheng Lei SpringBootpicturesMybatis Overall Framework 2.png)

1-Mybatis implementation (1)

Summary of usage steps

1) Configure mybatis-config.xml global configuration file (1, data source, 2, external mapper)
2) Create SqlSessionFactory
3) Create SqlSession objects from SqlSessionFactory
4) Operating database CRUD through SqlSession
5) Call session.commit() to commit a transaction
6) Call session.close() to close session==

directory structure

] (C:Users 1022468 3D ocuments Notes_Cheng Lei SpringBootpicturesImage 2019-11-13-13-58-29-001.png)

To configure

<POM>Dependency

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.18</version>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.2.8</version>
</dependency>

<mybatis-config.xml>global configuration 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">
<!-- Root Label -->
<configuration>
    <properties>
    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatisdemo?serverTimezone=UTC"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
    </properties>

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING" />
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!-- Environment, you can configure multiple, default: Specify which environment to use -->
    <environments default="test">
        <!-- id: Unique Identification -->
        <environment id="test">
            <!-- Transaction Manager, JDBC Type Transaction Manager -->
            <transactionManager type="JDBC" />
            <!-- Data Source, Pool Type Data Source -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mybatisdemo?serverTimezone=UTC" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>

        <environment id="development">
            <!-- Transaction Manager, JDBC Type Transaction Manager -->
            <transactionManager type="JDBC" />
            <!-- Data Source, Pool Type Data Source -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" /> <!-- Configured properties,So you can reference it directly -->
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
    <!-- Establish mapping relationships -->
    <mappers>
        <mapper resource="mappers/MyMapper.xml" />
        <mapper resource="mappers/UserDaoMapper.xml" />
        <mapper resource="mappers/UserMapper.xml" />
    </mappers>
    

</configuration>

Source Files and Implementation

Step 1: <mybatis-config.xml>Global Configuration File

Where: Key mapping rules:

<mappers>
    <!--Map mapper file to global configuration file-->
    <mapper resource="mappers/UserDaoMapper.xml" />
</mappers>

Step 2: Write a data class

Build packages once and write java classes

POJO:User.java
package com.onebooming.pojo;

import java.util.Date;

public class User {
    private String id;
    private String username;
    private String password;
    private String name;
    private Integer age;
    private Integer sex;
    private Date birthday;
    private String created;
    private String updated;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getSex() {
        return sex;
    }

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

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getCreated() {
        return created;
    }

    public void setCreated(String created) {
        this.created = created;
    }

    public String getUpdated() {
        return updated;
    }

    public void setUpdated(String updated) {
        this.updated = updated;
    }

    @Override
    public String toString() {
        return "user{" +
                "id='" + id + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                ", birthday=" + birthday +
                ", created='" + created + '\'' +
                ", updated='" + updated + '\'' +
                '}';
    }
}
dao:UserDao.java
package com.onebooming.dao;

import com.onebooming.pojo.User;

import java.util.List;

public interface UserDao {
    /**
     * Query user information based on id
     * @param id
     * @return
     */
    public User queryUserById(String id);

    /**
     * Query all user information
     * @return
     */
    public List<User> queryUserAll();

    /**
     * New Users
     * @param User
     */
    public void insertUser(User user);

    /**
     * Update user information
     * @param User
     */
    public void updateUser(User user);

    /**
     * Delete user information based on id
     * @param id
     */
    public void deleteUser(String id);
}
daoImpl:UserDaoImpl

Implementation class for UserDao interface:

package com.onebooming.dao.daoImpl;

import com.onebooming.dao.UserDao;
import com.onebooming.pojo.User;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserDaoImpl implements UserDao {
    public SqlSession sqlSession;

    public UserDaoImpl(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    public User queryUserById(String id) {
        return this.sqlSession.selectOne("UserDao.queryUserById", id);
    }

    public List<User> queryUserAll() {
        return this.sqlSession.selectList("UserDao.queryUserAll");
    }

    public void insertUser(User user) {
         this.sqlSession.insert("UserDao.insertUser", user);
    }

    public void updateUser(User user) {
        this.sqlSession.update("UserDao.updateUser", user);
    }

    public void deleteUser(String id) {
        this.sqlSession.delete("UserDao.deleteUser", id);
    }
}

Step 3: Create the corresponding mapper.xml file

UserDaoMapper: (This file is generally centralized in the resource-->mappers path)

Note: Be sure to modify the paths to the corresponding namespace and resultType and paramType

<mapper namespace="UserDao">

Namespace: namespace, freely written, generally guaranteed to be unique

<select id="queryUserById" resultType="com.onebooming.pojo.User">

Method name of CRUD in id:UserDao, must match exactly

resultType: The return value type of the method

Complete:

<?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:Root tag, namespace: Namespaces, freely written, generally guaranteed to be unique -->
<mapper namespace="UserDao">
    <!-- statement,Content: sql Sentence. id: Unique Identity, Write Anyway, Keep Unique in Same Namespace
       resultType: sql Encapsulation type of statement query result set,tb_user This is the table in the database
     -->
    <!--<select id="queryUserById" resultType="com.zpc.mybatis.pojo.User">-->
    <!--select * from tb_user where id = #{id}-->
    <!--</select>-->

    <!--aliases-->
    <select id="queryUserById" resultType="com.onebooming.pojo.User">
      select
       tuser.id as id,
       tuser.user_name as username,
       tuser.password as password,
       tuser.name as name,
       tuser.age as age,
       tuser.birthday as birthday,
       tuser.sex as sex,
       tuser.created as created,
       tuser.updated as updated
       from
       tb_user tuser
       where tuser.id = #{id};
   </select>

    <select id="queryUserAll" resultType="com.onebooming.pojo.User">
        select * from tb_user;
    </select>

    <!--insert data-->
    <insert id="insertUser" parameterType="com.onebooming.pojo.User">
        INSERT INTO tb_user (
        id,
        user_name,
        password,
        name,
        age,
        sex,
        birthday,
        created,
        updated
        )
        VALUES
        (
        #{id},
        #{username},
        #{password},
        #{name},
        #{age},
        #{sex},
        #{birthday},
        now(),
        now()
        );
    </insert>

    <update id="updateUser" parameterType="com.onebooming.pojo.User">
        UPDATE tb_user
        <trim prefix="set" suffixOverrides=",">
            <if test="username!=null">user_name = #{username},</if>
            <if test="password!=null">password = #{password},</if>
            <if test="name!=null">name = #{name},</if>
            <if test="age!=null">age = #{age},</if>
            <if test="sex!=null">sex = #{sex},</if>
            <if test="birthday!=null">birthday = #{birthday},</if>
            updated = now(),
        </trim>
        WHERE
        (id = #{id});
    </update>

    <delete id="deleteUser">
        delete from tb_user where id=#{id}
    </delete>
</mapper>

Step 4: Add a map to the global configuration file

<mappers>
    <!--Map mapper file to global configuration file-->
    <mapper resource="mappers/UserDaoMapper.xml" />
</mappers>

Step 5: Write a test class

The important point is: take the global configuration file -- read the configuration file -- build the SQLSessionFactory object -- get the SqlSession object -- map the UserDao object

sql statement in xml is hard-coded into java code

    public UserDao userDao;
    public SqlSession sqlSession;

    @Before
    public void setUp() throws Exception {
        //maybatis-config.xml
        String resource = "mybatis-config.xml";
        //Read Configuration File
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //Build SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //Get SqlSession
        sqlSession = sqlSessionFactory.openSession();
        this.userDao = new UserDaoImpl(sqlSession);
    }
package com.onebooming.dao;

import com.onebooming.dao.daoImpl.UserDaoImpl;
import com.onebooming.pojo.User;
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.Before;
import org.junit.Test;

import java.io.InputStream;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static org.junit.Assert.*;

public class UserDaoTest {
    public UserDao userDao;
    public SqlSession sqlSession;

    @Before
    public void setUp() throws Exception {
        //maybatis-config.xml
        String resource = "mybatis-config.xml";
        //Read Configuration File
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //Build SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //Get SqlSession
        sqlSession = sqlSessionFactory.openSession();
        this.userDao = new UserDaoImpl(sqlSession);
    }

    @Test
    public void queryUserById() {
        System.out.println(this.userDao.queryUserById("1"));
    }

    @Test
    public void queryUserAll() {
        List<User> userList = this.userDao.queryUserAll();
        for(User user : userList){
            System.out.println(user);
        }
    }

    @Test
    public void insertUser() throws Exception {
        User user = new User();
        user.setAge(16);
        //user.setBirthday((new Date("1949/10/01"));
        String str = "1994-10-01";
        Date date = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        date = dateFormat.parse(str);
        user.setBirthday(date);
        user.setName("Boe Wang");
        user.setPassword("root");
        user.setId("5");
        user.setUsername("Onebooming");
        user.setSex(5);
        this.userDao.insertUser(user);
        this.sqlSession.commit();
    }

    @Test
    public void updateUser() {
        User user = new User();
        user.setBirthday(new Date());
        user.setName("Jingpeng");
        user.setPassword("654321");
        user.setSex(1);
        user.setUsername("evanjin");
        user.setId("1");
        this.userDao.updateUser(user);
        this.sqlSession.commit();
    }

    @Test
    public void deleteUser() {
        this.userDao.deleteUser("2");
        this.sqlSession.commit();
    }
}

2-Mybatis implementation (2)

Dynamic proxy for interfaces: write-only interfaces and apper.xml

Summary of usage steps

(1) Write entity classes (pojo--User)

(2) Writing interfaces (dao--UserMapper)

(3) Write mapper.xml (mappers--UserMapper.xml)

(4) Call interface to implement CRUD

directory structure

] (C:Users10224683D ocuments Notes_Cheng Lei SpringBootpicturesImage 2019-11-13-14-43-48-001.png)

Source Files and Implementation: Dynamic Proxy for Interfaces

Step 1: Global Profile

Same as implementation

Step 2: Write a data class

pojo: User.java
package com.onebooming.pojo;

import java.util.Date;

public class User {
    private String id;
    private String username;
    private String password;
    private String name;
    private Integer age;
    private Integer sex;
    private Date birthday;
    private String created;
    private String updated;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getSex() {
        return sex;
    }

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

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getCreated() {
        return created;
    }

    public void setCreated(String created) {
        this.created = created;
    }

    public String getUpdated() {
        return updated;
    }

    public void setUpdated(String updated) {
        this.updated = updated;
    }

    @Override
    public String toString() {
        return "user{" +
                "id='" + id + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                ", birthday=" + birthday +
                ", created='" + created + '\'' +
                ", updated='" + updated + '\'' +
                '}';
    }
}
dao:UserMapper.java (interface)

Design CRUD methods in this interface

package com.onebooming.dao;

import com.onebooming.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * Implement dynamic proxy for Mybatis
 */
public interface UserMapper {
    /**
     * Login (pass in the specified parameter name directly using the comment)
     * @param username
     * @param password
     * @return
     */
    public User login(@Param("username") String username,@Param("password") String password);

    /**
     * Query user information based on table name (specify incoming parameter name directly using annotations)
     * @param tablename
     * @return
     *
     */
    public List<User> queryUserByTablename(@Param("tablename") String tablename);

    /**
     * Query user information based on Id
     * @param id
     * @return
     */
    public User queryById(String id);

    /**
     * Query all user information
     * @return
     */
    public List<User> queryUserAll();

    /**
     * Add User Information
     * @param user
     */
    public void insertUser(User user);

    /**
     * Update user information based on id
     * @param user
     *
     */
    public void updateUser(User user);

    /**
     * Delete user information based on id
     * @param id
     */
    public void deleteUserById(String id);
}

Step 3: Create the corresponding mapper.xml file

(UserMapper.xml)

Note1:namespace: Namespace, freely written, generally guarantees that the namespace is unique. In order to use interface dynamic proxy, the full path name of the interface must be here

Note2:1. #{}, the precompiled way of preparedstatement, uses placeholder substitution to prevent sql injection, any parameter name can be accepted when a parameter is in use; 2. ${}, ordinary Statement, string splicing directly does not prevent sql injection, this method must be used when a parameter is in use to receive parameters

<?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:Root tag, namespace: Namespace, Write freely, generally guarantees that the namespace is unique. In order to use interface dynamic proxy, the full path name of the interface must be here-->
<mapper namespace="com.onebooming.dao.UserMapper">
    <!--
       1.#{}, a precompiled way of preparedstatement, using placeholder substitution to prevent sql injection, any parameter name can be accepted when a parameter
       2.${},Ordinary Statement,String splicing directly, not preventable sql Injection, a parameter, must be used ${value}Receive parameters
     -->

    <select id="queryUserByTablename" resultType="com.onebooming.pojo.User">
        select * from ${tablename}
    </select>

    <select id="login" resultType="com.onebooming.pojo.User">
        select * from tb_user where user_name = #{username} and password = #{password}
    </select>

    <!-- statement,Content: sql Sentence.
       id: Unique identity, freely written, unique under the same namespace, consistent with method name after using dynamic proxy
       resultType: sql Statement queries the encapsulation type of the result set, which is the same as the return type of the method after using the dynamic proxy. resultMap: Either-or
       parameterType: Parameter type, which is the same as the method's parameter type after using dynamic proxy
     -->
    <select id="queryUserById" resultType="com.onebooming.pojo.User">
        select * from tb_user where id = #{id}
    </select>

    <select id="queryUserAll" resultType="com.onebooming.pojo.User">
        select * from tb_user
    </select>

    <!-- Added Statement
       id: Unique identity, freely written, unique under the same namespace, consistent with method name after using dynamic proxy
       parameterType: Parameter type, which is the same as the method's parameter type after using dynamic proxy
       useGeneratedKeys:Turn on Primary Key Writeback
       keyColumn: Specify the primary key for the database
       keyProperty: Corresponding Primary Key pojo Property Name
     -->
    <insert id="insertUser" useGeneratedKeys="true" keyColumn="id" keyProperty="id" parameterType="com.onebooming.pojo.User">
        insert into tb_user(id,user_name,password,name,age,sex,birthday,created,updated)
        values (
        #{id},
        #{username},
        #{password},
        #{name},
        #{age},
        #{sex},
        #{birthday},
        NOW(),
        NOW()
        );
    </insert>

    <!--
     //Updated statement
     id: Unique identity, freely written, unique under the same namespace, consistent with method name after using dynamic proxy
     parameterType: Parameter type, which is the same as the method's parameter type after using dynamic proxy
   -->
    <update id="updateUser" parameterType="com.onebooming.pojo.User">
        update tb_user
        <trim prefix="set" suffixOverrides=",">
            <if test="username!=null">user_name = #{username},</if>
            <if test="password!=null">password = #{password},</if>
            <if test="name!=null">name = #{name},</if>
            <if test="age!=null">age = #{age},</if>
            <if test="sex!=null">sex = #{sex},</if>
            <if test="birthday!=null">birthday = #{birthday},</if>
            updated = now(),
        </trim>
        where (id = #{id});
    </update>
    <!--
       //Deleted statement
       id: Unique identity, freely written, unique under the same namespace, consistent with method name after using dynamic proxy
       parameterType: Parameter type, which is the same as the method's parameter type after using dynamic proxy
     -->
    <delete id="deleteUserById" parameterType="java.lang.String">
        delete from tb_user where id=#{id}
    </delete>
</mapper>

Step 4: Add a map to the global configuration file

Declare the UserMapper.xml file in the mybatis-config.xml file

    <mappers>
        <mapper resource="mappers/UserDaoMapper.xml" />
        <mapper resource="mappers/UserMapper.xml" />
    </mappers>

Step 5: Write a test class

package com.onebooming.dao;

import com.onebooming.pojo.User;
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.Before;
import org.junit.Test;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class UserMapperTest {
    public UserMapper userMapper;
    @Before
    public void setUp() throws Exception {
        //Specify Profile
        String resource = "mybatis-config.xml";
        //Read Configuration File
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //Building sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //Get SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //1. The namespace of the mapping file must be the full path of the mapper interface
        //2. The id of the statement of the mapping file must match the method name of the mapper interface
        //3.Statemen's resultType must match the return type of the mapper interface method
        //4. The parameterType of the Statement must match (not necessarily) the parameter type of the mapper interface method
        this.userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void login() {
        System.out.println(this.userMapper.login("a","b"));
    }

    @Test
    public void queryUserByTablename() {
        List<User> userList = this.userMapper.queryUserByTablename("tb_user");
        for(User user: userList){
            System.out.println(user);
        }
    }

    @Test
    public void queryById() {
        System.out.println(this.userMapper.queryById("2"));
    }

    @Test
    public void queryUserAll(){
        List<User> userList = this.userMapper.queryUserAll();
        for(User user : userList){
            System.out.println(user);
        }
    }

    @Test
    public void insertUser() throws ParseException {
        User user = new User();
        user.setId("6");
        user.setUsername("mayun");
        user.setPassword("123456");
        user.setAge(25);
        user.setSex(1);
        String str = "1995-10-01";
        Date date = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        date = dateFormat.parse(str);
        user.setBirthday(date);
        this.userMapper.insertUser(user);
        System.out.println(user.getId());
    }



    @Test
    public void updateUser() {
        User user = new User();
        user.setBirthday(new Date());
        user.setName("Fuck you");
        user.setPassword("123456");
        user.setSex(0);
        user.setUsername("hehe");
        user.setId("2");
        this.userMapper.updateUser(user);

    }

    @Test
    public void deleteUserById() {
        this.userMapper.deleteUserById("1");
    }
}

3-Mybatis implementation (3)

Mapper interface notes for mybatis notes

This method only needs @Mapper annotation for the interface and does not need to write mapper.xml file to implement CRUD directly

To configure

pom dependency

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.onebooming</groupId>
    <artifactId>boe-cloud-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>boe-cloud-service</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.11</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.29</version>
        </dependency>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

core

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

configuration file

application.propertities

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql:///boecloudservice?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=root
mybatis.config-location=classpath:/mybatis-config.xml

server.port=8081
logging.level.org.springframework.security=info

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">
<!-- Root Label -->
<configuration>
    <properties>
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/boecloudservice?serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </properties>

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
</configuration>

Source files and implementation: writing interfaces directly using annotations

entities layer: entity class

package com.onebooming.boecloudservice.bean;

import java.util.Date;

/**
 * Virtual Machine Entity Class
 * @author Onebooming
 */
public class VirtualMachine {
    public Long id;//Virtual Machine ID
    public String machineName;//Virtual Machine Name
    public String vmPathName;//Virtual Machine Path Name
    public String guestFullName;//Client Full Name
    public String instanceUuid;//Instance UUID
    public String annotation;//Notes
    public String powerState;//Power status
    public String toolsStatus;//Tool Status
    public String ipAddress;//IP Address
    public Integer memorySizeMB;//Memory size
    public Integer numCpu;//Number of CPU cores
    public Integer numVirtualDisks;//Number of virtual hard disks
    public Date bootTime;//boot time
    public String exsiIp;//exsiIP

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getMachineName() {
        return machineName;
    }

    public void setMachineName(String machineName) {
        this.machineName = machineName;
    }

    public String getVmPathName() {
        return vmPathName;
    }

    public void setVmPathName(String vmPathName) {
        this.vmPathName = vmPathName;
    }

    public String getGuestFullName() {
        return guestFullName;
    }

    public void setGuestFullName(String guestFullName) {
        this.guestFullName = guestFullName;
    }

    public String getInstanceUuid() {
        return instanceUuid;
    }

    public void setInstanceUuid(String instanceUuid) {
        this.instanceUuid = instanceUuid;
    }

    public String getAnnotation() {
        return annotation;
    }

    public void setAnnotation(String annotation) {
        this.annotation = annotation;
    }

    public String getPowerState() {
        return powerState;
    }

    public void setPowerState(String powerState) {
        this.powerState = powerState;
    }

    public String getToolsStatus() {
        return toolsStatus;
    }

    public void setToolsStatus(String toolsStatus) {
        this.toolsStatus = toolsStatus;
    }

    public String getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }

    public Integer getMemorySizeMB() {
        return memorySizeMB;
    }

    public void setMemorySizeMB(Integer memorySizeMB) {
        this.memorySizeMB = memorySizeMB;
    }

    public Integer getNumCpu() {
        return numCpu;
    }

    public void setNumCpu(Integer numCpu) {
        this.numCpu = numCpu;
    }

    public Integer getNumVirtualDisks() {
        return numVirtualDisks;
    }

    public void setNumVirtualDisks(Integer numVirtualDisks) {
        this.numVirtualDisks = numVirtualDisks;
    }

    public Date getBootTime() {
        return bootTime;
    }

    public void setBootTime(Date bootTime) {
        this.bootTime = bootTime;
    }

    public String getExsiIp() {
        return exsiIp;
    }

    public void setExsiIp(String exsiIp) {
        this.exsiIp = exsiIp;
    }

    @Override
    public String toString() {
        return "VirtualMachine{" +
                "id=" + id +
                ", machineName='" + machineName + '\'' +
                ", vmPathName='" + vmPathName + '\'' +
                ", guestFullName='" + guestFullName + '\'' +
                ", instanceUuid='" + instanceUuid + '\'' +
                ", annotation='" + annotation + '\'' +
                ", powerState='" + powerState + '\'' +
                ", toolsStatus='" + toolsStatus + '\'' +
                ", ipAddress='" + ipAddress + '\'' +
                ", memorySizeMB=" + memorySizeMB +
                ", numCpu=" + numCpu +
                ", numVirtualDisks=" + numVirtualDisks +
                ", bootTime=" + bootTime +
                ", exsiIp='" + exsiIp + '\'' +
                '}';
    }
}

dao layer: interface

package com.onebooming.boecloudservice.dao;

import com.onebooming.boecloudservice.bean.VirtualMachine;
import org.apache.ibatis.annotations.*;

import java.util.List;


@Mapper
public interface VirtualMachineDao {
    /**
     * Increase Records
     * @param virtualMachine
     */
    /**
     * Use Option for properties of select tags corresponding to XML settings
     * userGeneratordKeys Indicates that a self-increasing primary key is to be used
     * keyProperty The field name used to specify the primary key field.
     * Self-increasing primary keys use the self-increasing feature at the bottom of the database.
     */
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into t_virtualmachine " +
            "(machineName,vmPathName,guestFullName,instanceUuid,annotation,powerState,toolsStatus,ipAddress,memorySizeMB,numCpu,numVirtualDisks,bootTime,exsiIp) " +
            "values (" +
            "#{machineName},#{vmPathName},#{guestFullName},#{instanceUuid},#{annotation},#{powerState},#{toolsStatus},#{ipAddress},#{memorySizeMB},#{numCpu},#{numVirtualDisks},#{bootTime},#{exsiIp})")
    public void addVirtualMachine(VirtualMachine virtualMachine);

    /**
     * Delete Record
     * @param id
     */
    @Delete("delete from t_virtualmachine where id=#{id}")
    public void deleteById(@Param("id") Long id);

    @Delete("delete * from t_virtualmachine")
    public void deleteAll();

    //Note the SQL statement: both set and where require a space in the data
    /**
     * Update Records--By id
     * @param virtualMachine
     */
    @Update("update t_virtualmachine set  " +
            "machineName=#{machineName}," +
            "vmPathName=#{vmPathName}," +
            "guestFullName=#{guestFullName}," +
            "instanceUuid=#{instanceUuid}," +
            "annotation=#{annotation}," +
            "powerState=#{powerState}," +
            "toolsStatus=#{toolsStatus}," +
            "ipAddress=#{ipAddress}," +
            "memorySizeMB=#{memorySizeMB}," +
            "numCpu=#{numCpu}," +
            "numVirtualDisks=#{numVirtualDisks}," +
            "bootTime=#{bootTime}," +
            "exsiIp=#{exsiIp} " +
            "where id=#{id}")
    public void updateVMById(VirtualMachine virtualMachine);

    /**
     * Update Record--By Machine Name--MachineName
     * @param virtualMachine
     */
    @Update("update t_virtualmachine set  " +
            "vmPathName=#{vmPathName}," +
            "guestFullName=#{guestFullName}," +
            "instanceUuid=#{instanceUuid}," +
            "annotation=#{annotation}," +
            "powerState=#{powerState}," +
            "toolsStatus=#{toolsStatus}," +
            "ipAddress=#{ipAddress}," +
            "memorySizeMB=#{memorySizeMB}," +
            "numCpu=#{numCpu}," +
            "numVirtualDisks=#{numVirtualDisks}," +
            "bootTime=#{bootTime}," +
            "exsiIp=#{exsiIp} " +
            "where machineName=#{machineName}")
    public void updateVMByName(VirtualMachine virtualMachine);

    /**
     * Query Records - Query by Machine Name
     */
    /**
     * ResultMap should be used for adapting when the field names of tables and the attribute names of objects are not too much the same and there are many fields in the table.
     */
    @Results(id = "VMResult", value = {
         @Result(id = true,column = "id",property = "id"),
         @Result(column = "machineName",property = "machineName"),
            @Result(column = "vmPathName",property = "vmPathName"),
            @Result(column = "guestFullName",property = "guestFullName"),
            @Result(column = "instanceUuid",property = "instanceUuid"),
            @Result(column = "annotation",property = "annotation"),
            @Result(column = "powerState",property = "powerState"),
            @Result(column = "toolsStatus",property = "toolsStatus"),
            @Result(column = "ipAddress",property = "ipAddress"),
            @Result(column = "memorySizeMB",property = "memorySizeMB"),
            @Result(column = "numCpu",property = "numCpu"),
            @Result(column = "numVirtualDisks",property = "numVirtualDisks"),
            @Result(column = "bootTime",property = "bootTime"),
            @Result(column = "exsiIp",property = "exsiIp"),
    })
    @Select("select * from t_virtualmachine where machineName = #{machineName}")
    public List<VirtualMachine> selectByName(@Param("machineName") String machineName);

    /**
     * Query records to get all virtual machine records
     * @return
     */
    @ResultMap("VMResult")
    @Select("select * from t_virtualmachine")
    public List<VirtualMachine> findAll();

    /**
     * Query records based on id
     * @param id
     * @return
     */
    @Select("select * from t_virtualmachine where id = #{id}")
    public VirtualMachine selectById(@Param("id") Long id);

}

Service layer:

package com.onebooming.boecloudservice.service;

import com.onebooming.boecloudservice.bean.VirtualMachine;
import com.onebooming.boecloudservice.dao.VirtualMachineDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Onebooming
 * @apiNote Virtual Machine Service Layer
 */

@Service
@Transactional
public class VirtualMachineService {
    @Autowired
    private VirtualMachineDao virtualMachineDao;

    /**
     * Service class: increase virtual machine information
     * @param virtualMachine
     */
    public void addNewVMInfo(VirtualMachine virtualMachine){
        virtualMachineDao.addVirtualMachine(virtualMachine);
    }

    /**
     * Service class: modify virtual machine information
     * @param virtualMachine
     */
    public void updateVMInfo(VirtualMachine virtualMachine){
        virtualMachineDao.updateVMByName(virtualMachine);
    }

    /**
     * Service class: delete virtual machine records based on id
     * @param id
     */
    public void deleteVMById(Long id){
        virtualMachineDao.deleteById(id);
    }

    /**
     * Service class: delete all virtual machine records
     */
    public void deleteAllVM(){
        virtualMachineDao.deleteAll();
    }

    /**
     * Service class: query all server records
     * @return
     */
    public List<VirtualMachine> findAll(){
        return virtualMachineDao.findAll();
    }

    /**
     * Service class: Query virtual machine records based on virtual machine name
     * @param name
     * @return
     */
    public List<VirtualMachine> findByName(String name){
        return virtualMachineDao.selectByName(name);
    }

    /**
     * Service class: query server class based on id
     * @param id
     * @return
     */
    public VirtualMachine findById(Long id){
        return virtualMachineDao.selectById(id);
    }
}

Be careful

ResultMap

ResultMap should be used for adapting when the field names of tables and the attribute names of objects are not too much the same and there are many fields in the table.

/**
 * Using ResultMap
 *
 * @param id
 * @return
 */
@Results(id = "VMResult", value = {
         @Result(id = true,column = "id",property = "id"),
         @Result(column = "machineName",property = "machineName"),
            @Result(column = "vmPathName",property = "vmPathName"),
            @Result(column = "guestFullName",property = "guestFullName"),
            @Result(column = "instanceUuid",property = "instanceUuid"),
            @Result(column = "annotation",property = "annotation"),
            @Result(column = "powerState",property = "powerState"),
            @Result(column = "toolsStatus",property = "toolsStatus"),
            @Result(column = "ipAddress",property = "ipAddress"),
            @Result(column = "memorySizeMB",property = "memorySizeMB"),
            @Result(column = "numCpu",property = "numCpu"),
            @Result(column = "numVirtualDisks",property = "numVirtualDisks"),
            @Result(column = "bootTime",property = "bootTime"),
            @Result(column = "exsiIp",property = "exsiIp"),
    })
    @Select("select * from t_virtualmachine where machineName = #{machineName}")
    public List<VirtualMachine> selectByName(@Param("machineName") String machineName);

@Results corresponds to a ResultMap in the XML and can be assigned an id that can be used elsewhere to reference it, such as if you want to reference the Result above: ==(<u>VMResult</u>)==

    /**
     * Query records to get all virtual machine records
     * @return
     */
    @ResultMap("VMResult")
    @Select("select * from t_virtualmachine")
    public List<VirtualMachine> findAll();

Use @ResultMap to reference an existing ResultMap, either defined in Java using the @Results annotation or in XML using the resultMap tag.

limit

Advantages of using interface annotations:

  1. Convenient and fast mapping statement writing

Disadvantages of using interface annotations:

1. For simpler configurations, when the interface is too complex, you can't get it.

     2. ** Dynamic SQL** is not available and has some chicken ribs.


4-Mybatis implementation (4)

@Mapper annotation + mapper.xml

Advantages: Flexibility to implement complex sql queries

Catalog

Because of the project content, it is not convenient to map here
Brief introduction:
bean package: PhysicServer.class
dao package: PhysicServerMapper.class
/resource/mappers/:PhysicServerMapper.xml

Source Files and Implementation

Step1 - Create SpringBoot Project

Step2-Add mybatis dependency

<!--mybatis rely on-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.2.1</version>
</dependency>
<!-- druid Alibaba Database Connection Pool -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.26</version>
</dependency>

Configuring Druid data sources in Step3-application.properties

# Master data source, default
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# Database Name
spring.datasource.url=jdbc:mysql:///boecloudservice?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT
# Database login account
spring.datasource.username=root
# Data Logon Password
spring.datasource.password=root
# Main Profile
mybatis.config-location=classpath:/mybatis-config.xml

# SpringBoot Application Service Access Port Number
server.port=8081
logging.level.org.springframework.security=info
# The following are additional settings for the Druid connection pool that apply to all of the above data sources
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# Configure how long to wait for a connection to timeout
spring.datasource.maxWait=60000
# Configure how often to do a check to detect idle connections that need to be closed in milliseconds
spring.datasource.timeBetweenEvictionRunsMillis=60000
# Configure a connection's minimum lifetime in milliseconds in the pool
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# Open the PSCache and specify the size of the PSCache on each connection
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# Configure filters intercepted by monitoring statistics, sql cannot be counted after removal,'wall'for firewall
spring.datasource.filters=stat,wall,log4j
# Turn on mergeSql functionality through the connectProperties property; slow SQL records
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# Merge monitoring data from multiple DruidDataSource s
#spring.datasource.useGlobalDataSourceStat=true

Step4-java Coding (bean+dao)

Entity class: PhysicServer

package com.onebooming.boecloudservice.bean;

import java.util.HashMap;

/**
 * CPU Server Class
 * @author Onebooming
 *
 */
public class PhysicServer {
    private Long id;//Device id
    private String name;//Device Name
    private String area;//Equipment Location
    private String datacenter;//Data Center
    private String position;//position
    private String height;//height
    private String brand;//brand
    private String type;//Model
    private String serialNumber;//serial number
    private String bIp;//Business IP
    private String mgmtIp;//Manage IP
    private String cpuName;//CPUming
    private int cpuNum;//Number of CPUs
    private HashMap<Integer, Integer> memoryMap;//Memory bar specifications and quantities
    //key; memory strip size (4G/8G/16G/32G...), value: number of memory strips
    private int memorySum;//Total memory
    private int storage;//Total Storage Space
    private HashMap<String, Integer> diskMap;//Disk specifications and quantities
    private String manufactor;//Manufacturer
    private String department;//Departments to which they belong
    private String user;//User
    private String maintainor;//Operations and maintenance personnel

    @Override
    public String toString() {
        return "PhysicServer{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", area='" + area + '\'' +
                ", datacenter='" + datacenter + '\'' +
                ", position='" + position + '\'' +
                ", height='" + height + '\'' +
                ", brand='" + brand + '\'' +
                ", type='" + type + '\'' +
                ", serialNumber='" + serialNumber + '\'' +
                ", bIp='" + bIp + '\'' +
                ", mgmtIp='" + mgmtIp + '\'' +
                ", cpuName='" + cpuName + '\'' +
                ", cpuNum=" + cpuNum +
                ", memoryMap=" + memoryMap +
                ", memorySum=" + memorySum +
                ", storage=" + storage +
                ", diskMap=" + diskMap +
                ", manufactor='" + manufactor + '\'' +
                ", department='" + department + '\'' +
                ", user='" + user + '\'' +
                ", maintainor='" + maintainor + '\'' +
                '}';
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public String getDatacenter() {
        return datacenter;
    }

    public void setDatacenter(String datacenter) {
        this.datacenter = datacenter;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getSerialNumber() {
        return serialNumber;
    }

    public void setSerialNumber(String serialNumber) {
        this.serialNumber = serialNumber;
    }

    public String getbIp() {
        return bIp;
    }

    public void setbIp(String bIp) {
        this.bIp = bIp;
    }

    public String getMgmtIp() {
        return mgmtIp;
    }

    public void setMgmtIp(String mgmtIp) {
        this.mgmtIp = mgmtIp;
    }

    public String getCpuName() {
        return cpuName;
    }

    public void setCpuName(String cpuName) {
        this.cpuName = cpuName;
    }

    public int getCpuNum() {
        return cpuNum;
    }

    public void setCpuNum(int cpuNum) {
        this.cpuNum = cpuNum;
    }

    public HashMap<Integer, Integer> getMemoryMap() {
        return memoryMap;
    }

    public void setMemoryMap(HashMap<Integer, Integer> memoryMap) {
        this.memoryMap = memoryMap;
    }

    public int getMemorySum() {
        return memorySum;
    }

    public void setMemorySum(int memorySum) {
        this.memorySum = memorySum;
    }

    public int getStorage() {
        return storage;
    }

    public void setStorage(int storage) {
        this.storage = storage;
    }

    public HashMap<String, Integer> getDiskMap() {
        return diskMap;
    }

    public void setDiskMap(HashMap<String, Integer> diskMap) {
        this.diskMap = diskMap;
    }

    public String getManufactor() {
        return manufactor;
    }

    public void setManufactor(String manufactor) {
        this.manufactor = manufactor;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getMaintainor() {
        return maintainor;
    }

    public void setMaintainor(String maintainor) {
        this.maintainor = maintainor;
    }
}

dao interface: PhysicServerMapper

package com.onebooming.boecloudservice.dao;

import com.onebooming.boecloudservice.bean.PhysicServer;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Onebooming
 * @apiNote Server Service Access Layer Class
 */

@Mapper
public interface PhysicServerMapper {
    /**
     * Increase Server Information
     * @param physicServer
     * @return
     */
    public void addServers(PhysicServer physicServer);

    /**
     * Update Server Information
     * @param physicServer
     * @return
     */
    public void updateServers(PhysicServer physicServer);

    /**
     * Delete server information based on id
     * @param id
     */
    public void deleteServersById(Long id);

    /**
     * Get all server information
     * @return
     */
    public List<PhysicServer> getAllServers();

    /**
     * Get from server name
     * @param name
     * @return
     */
    public PhysicServer getServerByName(@Param("name") String name);


}

Writing Step5-mapper.xml File

  • Create data directly in mysql: boecloudserver
  • Setting up a data table in a database: t_phsicserver
  • [] = = Note that the field names in the data are best aligned with the attribute names in the HysicServer.java entity class, preferably duplicated in the past, so that spelling errors in many sql statements can be avoided.==

Figure

Write the corresponding mapper file at the same time: PhysicServerMapper.xml
**Note: The most important thing here is the absolute path to namespace:'com.onebooming.boecloudservice.dao.PhysicServerMapper'
And parameter types in sql statements, path to return value type**

<?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.onebooming.boecloudservice.dao.PhysicServerMapper">
    <insert id="addServers" parameterType="com.onebooming.boecloudservice.bean.PhysicServer" useGeneratedKeys="true" keyProperty="id">
        insert into t_physicservers(name,area,datacenter,position,height,brand,type,serialnumber,
        bIp,mgmtIp,cpuname,cpunum,memorysum,storage,manufactor,department,user,maintainor)
         values
        (#{name},#{area},#{datacenter},#{position},#{height},#{brand},#{type},#{serialNumber},
        #{bIp},#{mgmtIp},#{cpuName},#{cpuNum},#{memorySum},#{storage},#{manufactor},#{department},#{user},#{maintainor})
    </insert>
    <update id="updateServers" parameterType="com.onebooming.boecloudservice.bean.PhysicServer">
        update t_physicservers set
        name=#{name},
        area=#{area},
        datacenter=#{datacenter},
        position=#{position},
        height=#{height},
        brand=#{brand},
        type=#{type},
        serialnumber=#{serialNumber},
        bIp=#{bIp},
        mgmtIp=#{mgmtIp},
        cpuname=#{cpuName},
        cpunum=#{cpuNum},
        memorysum=#{memorySum},
        storage=#{storage},
        manufactor=#{manufactor},
        department=#{department},
        user=#{user},
        maintainor=#{maintainor}
        where id=#{id}
    </update>
    <delete id="deleteServersById" parameterType="java.lang.Long">
        delete from t_physicservers where id=#{id}
    </delete>
    <select id="getAllServers" resultType="com.onebooming.boecloudservice.bean.PhysicServer">
        select * from t_physicservers
    </select>
    <select id="getServerByName" parameterType="String" resultType="com.onebooming.boecloudservice.bean.PhysicServer">
        select * from t_physicservers where name=#{name}
    </select>
</mapper>

Declare the PhysicServerMapper.xml file in the mybatis-config.xml file

    <mappers>
        <mapper resource="mappers/ArticleMapper.xml" />
        <mapper resource="mappers/CategoryMapper.xml" />
        <mapper resource="mappers/PhysicServerMapper.xml" />
        <mapper resource="mappers/TagsMapper.xml" />
        <mapper resource="mappers/RolesMapper.xml" />
        <mapper resource="mappers/UserMapper.xml" />

    </mappers >

Next, you can test it.

Postnote

As for Mybatis, I'm also a beginner. I've been learning for almost two weeks and I've also trampled in projects.So I integrated my own practice steps.The errors in the article should also be corrected in time.

Keywords: Java Mybatis xml Spring

Added by cirma on Thu, 14 Nov 2019 06:34:43 +0200