springboot integration mybats

Preface

Recently, mybatiesplus was integrated with springboot( SpringBoot integrates mybatis plus )In fact, it is known that the steps of integration are not complicated. Today, try integrating mybats with springboot. This paper uses the xml configuration method. Although the annotation method is simple, it is not so simple and fast to write complex sql. In normal business, most of them require complex sql to complete business needs. OK, let's go straight to the code.

Overall catalog of the project

1. pom.xml dependency

The most important thing is the dependency of mysql driver package, where Druid data source is used.

<?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.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example.mybaties</groupId>
    <artifactId>springbootmybaties</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootmybaties</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <mysql-connector-java.version>8.0.11</mysql-connector-java.version>
        <druid.version>1.1.14</druid.version>
    </properties>

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--mysql rely on-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-java.version}</version>
        </dependency>
        <!--mysql Two level cache-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-ehcache</artifactId>
            <version>1.0.0</version>
        </dependency>
        <!-- Druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.version}</version>
        </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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. application.yml configuration file

server:
  port: 8001
logging:
  config: classpath:logback-spring.xml
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
    username: root
    password: root1234
    driver-class-name: com.mysql.cj.jdbc.Driver
    # Using the Druid data source
    type: com.alibaba.druid.pool.DruidDataSource
mybatis:
  mapper-locations: classpath:mapper/*.xml   #Scanned xml path
  type-aliases-package: com.example.mybaties.entity  #Scanned entity
  configuration:
    #Convert underlined to hump
    map-underscore-to-camel-case: true


3. user.java and baseplusentity (base class)

package com.example.mybaties.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

/**
 * <p>
 * User table
 * </p>
 *
 * @author lst
 * @since 2019-04-08
 */
@Data
public class User extends BasePlusEntity {

    /**
     * Login name
     */
    private String loginName;
    /**
     * Password
     */

    private String passWord;
    /**
     * User's real name
     */

    private String userName;
    /**
     * ID card No.
     */

    private String idCard;
    /**
     * Nation
     */
    private String nation;
    /**
     * Gender
     */
    private String sex;
    /**
     * Birthday
     */
    private String birthday;
    /**
     * Political outlook
     */

    private String politicsFace;
    /**
     * Head address
     */

    private String headPicture;
    /**
     * User status
     */

    private String userStatus;
    /**
     * Title
     */
    private String title;
    /**
     * Office
     */

    private String officeAddr;
    /**
     * Office phone
     */

    private String officePhone;
    /**
     * User's company list
     */

    private String userOrgs;
    /**
     * User's unit
     */

    private String userOrg;
    /**
     * Phone number
     */

    private String mobilPhone;
    /**
     * mail
     */
    private String email;
    /**
     * Spare mobile phone
     */

    private String mobilPhone2;
    /**
     * Virtual short
     */

    private String virtualNum;

    /**
     * Name of the window handler reserved when printing the form
     */

    private String printUserName;

    /**
     * Phone number of the person handling the reserved window when printing the form
     */

    private String printPhone;

    /**
     * Last login time
     */


    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date lastLogin;

    /**
     * Login ip.
     */

    private String ip;
    /**
     * province of birth
     */
    private String province;
    /**
     * City
     */
    private String city;
    /**
     * Detailed address
     */
    private String address;
    /**
     * Zip code
     */

    private String postCode;


    @Override
    public String toString() {
        return "User{" +
                "loginName=" + loginName +
                ", passWord=" + passWord +
                ", userName=" + userName +
                ", idCard=" + idCard +
                ", nation=" + nation +
                ", sex=" + sex +
                ", birthday=" + birthday +
                ", politicsFace=" + politicsFace +
                ", headPicture=" + headPicture +
                ", userStatus=" + userStatus +
                ", title=" + title +
                ", officeAddr=" + officeAddr +
                ", officePhone=" + officePhone +
                ", userOrgs=" + userOrgs +
                ", userOrg=" + userOrg +
                ", mobilPhone=" + mobilPhone +
                ", email=" + email +
                ", mobilPhone2=" + mobilPhone2 +
                ", virtualNum=" + virtualNum +
                ", province=" + province +
                ", city=" + city +
                ", address=" + address +
                ", postCode=" + postCode +
                ", id=" + id  +
                ", remarks=" + remarks +
                ", createBy=" + createBy +
                ", createDate=" + createDate +
                ", updateBy=" + updateBy  +
                ", updateDate=" + updateDate +
                ", delFlag=" + delFlag  +
                '}';
    }
}



package com.example.mybaties.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;

/**
 * Basic entity class
 *
 * @author lst
 * @since 2019-12-17
 */
@Data
public class BasePlusEntity implements Serializable {

    protected String id;

    /**
     * Remarks information
     */
    protected String remarks;


    /**
     * creator
     */
//    @JsonIgnore
    protected String createBy;

    /**
     * Date of creation
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    protected Date createDate;

    /**
     * Reneer
     */
//    @JsonIgnore
    protected String updateBy;

    /**
     * Update date
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    protected Date updateDate;

    /**
     * 0 Normal, 1 delete
     */
    @JsonIgnore
    protected String delFlag;


    public BasePlusEntity(String id) {
        this();
        this.id = id;
    }

    public BasePlusEntity() {
    }

    @Override
    public String toString() {
        return "BasePlusEntity{" +
                "id='" + id + '\'' +
                ", remarks='" + remarks + '\'' +
                ", createBy='" + createBy + '\'' +
                ", createDate=" + createDate +
                ", updateBy='" + updateBy + '\'' +
                ", updateDate=" + updateDate +
                ", delFlag='" + delFlag + '\'' +
                '}';
    }
}

4. UserMapper.java and mapped UserMapper.xml

The second level cache of mybats used here.

package com.example.mybaties.mapper;


import com.example.mybaties.entity.User;
import org.apache.ibatis.annotations.Mapper;

/**
 * <p>
 * User table Mapper interface
 * </p>
 *
 * @author lst
 * @since 2019-04-08
 */
@Mapper
public interface UserMapper {

    /**
     * Get user details
     *
     * @param uid
     * @return
     */
    User getUser(String uid);
}


<?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.example.mybaties.mapper.UserMapper">
    <!-- Enable L2 cache -->
    <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>

    <select id="getUser" parameterType="java.lang.String" resultType="com.example.mybaties.entity.User">
        SELECT a.* FROM sys_user a where  a.del_flag='0' and a.id=#{uid}
    </select>

</mapper>


5. UserService.java interface and UserServiceImpl.java implementation class

package com.example.mybaties.service;

import com.example.mybaties.entity.User;

/**
 * @author lst
 * @version 1.0
 * @Description: User table
 * @date 2019 April 9, 2008 18:23
 */
public interface UserService {

    /**
     * Get user details
     * @param userId User id
     * @return
     */
    User getUser(String userId);
}




package com.example.mybaties.service.impl;

import com.example.mybaties.entity.User;
import com.example.mybaties.mapper.UserMapper;
import com.example.mybaties.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author lst
 * @version 1.0
 * @Description: User table implementation layer
 * @date 2019 April 9, 2008 18:23
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * Get user details
     * @param userId User id
     * @return
     */
    @Override
    public User getUser(String userId) {

        User user = userMapper.getUser(userId);

        return user;
    }
}

6. UserController interface (test)

package com.example.mybaties.controller;

import com.example.mybaties.entity.User;
import com.example.mybaties.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author LST
 * @version 1.0
 * @Description: user management
 * @date 2019-12-28 16:22
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * Get user details
     * @param userId User id
     * @return
     */
    @GetMapping(value = "/{userId}", produces = "application/json; charset=utf-8")
    public User getUser(@PathVariable("userId") String userId) {
        return userService.getUser(userId);
    }
}

7. Start the application test.

package com.example.mybaties;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootmybatiesApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootmybatiesApplication.class, args);
    }

}

Before querying, execute the sql file in the project, create the user table and initialize part of the data, and directly request with the browser http://127.0.0.1:8001/user/0ac94d4eab22610c71af9a02bd4e296c Yes. The following diagram.

Then check the log of the console. You can see that when you request the second time or later, you can directly read the current user data from the cache. And every time you increase the request, the probability of cache hits will be higher and the matching will be more accurate.

The above content can be used for beginners to build a simple query function of mybatis.

Partners who need source code can go to download by themselves, and attach the download address: https://download.csdn.net/download/qq_33612228/12101075

 

Published 12 original articles, praised 7, visited 456
Private letter follow

Tags: Java Mybatis Spring MySQL

Posted on Mon, 13 Jan 2020 19:25:08 -0800 by TubeRev