This is the 27th day of my participation in the First Challenge 2022

Introduction to the

This article will explain in detail how to set up a Spring Boot Mybatis environment, involving dependency configuration and sample code and test related code

Based on Spring Boot 2.3.4, Junit5

Step-by-step instructions

The final directory structure of the whole project is as follows, adding files or new directory reference:

└ ─ SRC ├ ─ the main │ ├ ─ Java │ │ └ ─ com │ │ └ ─ mall │ │ └ ─ MallWeb │ │ ├ ─ controllers │ │ ├ ─ mapper │ │ ├ ─ model │ │ └ ─ services │ ├ ─ ├ ─ garbage, ├ ─test├ ─ Java └─com └─MallWeb └Copy the code

Database initialization statement

The initialization statements for database tables are all below and can be modified to suit your needs

CREATE DATABASE  IF NOT EXISTS `mall`;

USE `mall`;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(16) NOT NULL,
  `password` varchar(16) NOT NULL,
  `phoneNumber` varchar(15) NOT NULL,
  `money` int(11) NOT NULL.PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
Copy the code

Build. gradle: dependency add

The following dependencies need to be added

  • ‘mysql: mysql connector – Java: 8.0.14’
  • ‘org. Mybatis. Spring. The boot: mybatis – spring – the boot – starter: 2.0.0’
  • ‘org. Projectlombok: lombok: 1.16.16’
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'

	// The MySQL database needs it
	implementation 'mysql: mysql connector - Java: 8.0.14'
	//	spring mybatis
	implementation 'org. Mybatis. Spring. The boot: mybatis - spring - the boot - starter: 2.0.0'
	// Lombok, automatic get and set generation for Entity instead of writing a bunch of get and set methods yourself
	implementation 'org. Projectlombok: lombok: 1.16.16'

	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage'.module: 'junit-vintage-engine'}}Copy the code

Application. properties: Configuration add

Driver-class-name = false; driver-class-name = false;

# gradle
# Mybatis config file location configuration
mybatis.config-location=classpath:mybatis/mybatis-config.xml
XML file location configuration for each table
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.type-aliases-package=com.neo.model

# database connection information configuration, change the database, user name and passwordspring.datasource.url=jdbc:mysql://localhost:3306/mall? serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8\
  &useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Springboot + mybatis setup to print SQL statements to the console
logging.level.com.mall.MallWeb.mapper=debug
Copy the code
# maven
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.014.</version>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0. 0</version>
</dependency>
Copy the code

The code

Mapper scanning configuration is configured in the inbound environment

Add a Mapper scan configuration to the entry function so that there is no need to add Mapper annotations to each Mapper, as follows:

package com.mall.MallWeb;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/ * * *@author lw
 */
@SpringBootApplication
@MapperScan("com.mall.MallWeb.mapper")
public class MallWebApplication {

	public static void main(String[] args) { SpringApplication.run(MallWebApplication.class, args); }}Copy the code

Writing entity classes

Create a Model folder under the code directory to store entities (database tables). Edit the entity class as follows:

ppackage com.mall.MallWeb.model;

import java.io.Serializable;

/ * * *@author lw
 */
public class User implements Serializable {

    private Long id;
    private String name;
    private String password;
    private String phoneNumber;
    private Long money;

    public User(String name, String password, String phoneNumber) {
        this.name = name;
        this.password = password;
        this.phoneNumber = phoneNumber;
        this.money = 0L;
    }

    @Override
    public String toString(a) {
        return id + "... "" + name + "... "" + password + "... "" + phoneNumber + "... "" + money;
    }

    public Long getId(a) {
        return id;
    }

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

    public String getName(a) {
        return name;
    }

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

    public String getPassword(a) {
        return password;
    }

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

    public String getPhoneNumber(a) {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public Long getMoney(a) {
        return money;
    }

    public void setMoney(Long money) {
        this.money = money; }}Copy the code

Mapper interface class

Create a Mapper folder and put mapper-related interface classes in it. Mapper: @repository: idea: bean

package com.mall.MallWeb.mapper;

import com.mall.MallWeb.model.User;
import org.springframework.stereotype.Repository;

import java.util.List;

/ * * *@author lw
 */
@Repository
public interface UserMapper {

    List<User> queryAll(a);
    User queryOne(Long id);
    void add(User user);
    void update(User user);
}

Copy the code

Mytatis configuration file mybatis-config.xml

Mybatis -config. XML file: 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">
<configuration>
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer" />
        <typeAlias alias="Long" type="java.lang.Long" />
        <typeAlias alias="HashMap" type="java.util.HashMap" />
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
        <typeAlias alias="ArrayList" type="java.util.ArrayList" />
        <typeAlias alias="LinkedList" type="java.util.LinkedList" />
    </typeAliases>
</configuration>
Copy the code

Table USERS queries the configuration file user.xml

Create a new folder resouce/mybatis/mapper, create a new file: user.xml, enter the following content:

<? 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.mall.MallWeb.mapper.UserMapper" >
    <resultMap id="BaseResultMap" type="com.mall.MallWeb.model.User" >
        <id column="id" property="id" jdbcType="BIGINT" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="phoneNumber" property="phoneNumber" jdbcType="VARCHAR"/>
        <result column="money" property="money" jdbcType="BIGINT" />
    </resultMap>

    <sql id="Base_Column_List" >
        id, name, password, phoneNumber, money
    </sql>

    <insert id="add" parameterType="com.mall.MallWeb.mapper.UserMapper" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO
            users
            (name, password, phoneNumber, money)
        VALUES
            (#{name}, #{password}, #{phoneNumber}, #{money})
    </insert>

    <update id="update" parameterType="com.mall.MallWeb.model.User">
        UPDATE
            users
        SET
        <trim suffixOverrides="," suffix="WHERE id = #{id}">
            <if test="name ! = null">name = #{name},</if>
            <if test="password ! = null">password = #{password},</if>
            <if test="phoneNumber ! = null">phoneNumber = #{phoneNumber},</if>
            <if test="money ! = null">money = #{money},</if>
        </trim>
    </update>

    <select id="queryAll" resultMap="BaseResultMap">
        SELECT
            <include refid="Base_Column_List" />
        FROM users
    </select>

    <select id="queryOne" resultType="com.mall.MallWeb.model.User" parameterType="java.lang.Long">
        SELECT
            <include refid="Base_Column_List" />
        FROM users
            <trim prefix="WHERE" prefixOverrides="AND |OR ">
            <if test="id ! = null">
                id = #{id}
            </if>
            <if test="user_id ! = null">
                and user_id = #{user_id}
            </if>
            <if test="status ! = null">
                and status = #{status}
            </if>
        </trim>
    </select>

</mapper>
Copy the code

Test file UserMapperTest

The approximate code is as follows:

RunWith has been removed in Junit5, replaced with ExtendWith. A real database is used in the test. All data rollback after the test is enabled to prevent test data from entering the database

package com.mall.MallWeb.mapper;

import com.mall.MallWeb.model.User;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@ExtendWith(SpringExtension.class)
@SpringBootTest
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    @Transactional
    public void addUserTest(a) {
        User user = new User("testUser"."testPassword"."testPhone");
        userMapper.add(user);
        assertuserMapper.queryAll().size() ! =0;
    }

    @Test
    public void queryTest(a) {
        List<User> users = userMapper.queryAll();
        assertusers.size() ! =0;
        for(User user: users) { System.out.println(user.toString()); }}@Test
    @Transactional
    public void updateTest(a) {
        User user = new User("testUser"."testPassword"."testPhone");
        userMapper.add(user);
        System.out.println(user.toString());

        User newUser = userMapper.queryOne(user.getId());
        System.out.println(newUser.toString());

        newUser.setName("updateUser");
        System.out.println(newUser.toString());

        userMapper.update(newUser);
        System.out.println(newUser.toString());

        User queryUser = userMapper.queryOne(user.getId());
        assert queryUser.getName().equals("updateUser"); }}Copy the code

The view file in the controllers directory is userController.java

package com.mall.MallWeb.controllers;

import com.mall.MallWeb.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/users")
    public Map users(a) {
        Map response = new HashMap();
        response.put("status"."success");
        response.put("users", userMapper.queryAll());
        returnresponse; }}Copy the code

Startup and test

Now start to run the program, use the browser to access link: http://localhost:8080/user/users

Being able to see data with or without data is successful (the following data is pre-inserted)

{
    "users": [{"id": 6."name": "testUser"."password": "testPasspword"."phoneNumber": "testPhone"."money": 0
        },
        {
            "id": 7."name": "testUser"."password": "testPasspword"."phoneNumber": "testPhone"."money": 0
        },
        {
            "id": 8."name": "testUser"."password": "testPasspword"."phoneNumber": "testPhone"."money": 0
        },
        {
            "id": 9."name": "testUser"."password": "testPasspword"."phoneNumber": "testPhone"."money": 0
        },
        {
            "id": 10."name": "testUser"."password": "testPassword"."phoneNumber": "testPhone"."money": 0
        },
        {
            "id": 11."name": "testUser"."password": "testPassword"."phoneNumber": "testPhone"."money": 0
        },
        {
            "id": 12."name": "testUser"."password": "testPassword"."phoneNumber": "testPhone"."money": 0}]."status": "success"
}
Copy the code

Refer to the link

  • -Reason Failed to determine a suitable driver class
  • Java connection to mysql failed on anchors Path does not chain with any of the trust anchors
  • Unit Testing and Integration Testing of SpringBoot+Mybatis Framework Project (Part 2)
  • Spring Boot(6) : How to use Mybatis gracefully
  • mybatis-spring-boot-test-autoconfigure
  • Idea inspects batis mapper bean wrong
  • Property ‘sqlSessionFactory’ or ‘sqlSessionTemplate’ are required in spring mock mvc test for spring boot with mybatis
  • Mybatis passes multiple parameters
  • MyBatis multi-parameter transfer Map example — MyBatis learning Notes 13
  • MyBatis multi-parameter transmission in four ways
  • Mybatis enables the console to print SQL statements
  • Mybatis SQL (INSERT, update, delete) return value problem