[BackEnd] SpringBoot integrates Mybatis to implement login and registration functions (suitable for beginners)

I. Introduction

The author uploaded the code to Gitee, and friends can directly clone the project locally.

Point location:https://gitee.com/cai-zijing/SpringBoot_Mybatis_Login_Demo.git

Let me tell you about a very easy-to-use plug-in called Gitee. Its main function is to visually interact with remote warehouses in IDEAL. 

 Enter the project address to solve project cloning in one step

 2. Project structure

3. Code

3.1 pom.xml 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.7.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>Login_Mybatis_Demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Login_Mybatis_Demo</name>
    <description>Login_Mybatis_Demo</description>
    <properties>
        <java.version>17</java.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.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

3.2 applicaiton.yml configuration file

Whether to rename application.propertie to application.yml according to personal preference

server:
  port: 9091

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/login?serverTimezone=UTC

mybatis:
  type-aliases-package: com.bcn.login_mybatis_demo.pojo
  mapper-locations: classpath:mapper/*.xml
  # Turn on camelCase
  configuration:
    map-underscore-to-camel-case: true

# Show sql
logging:
  level:
    com:
      example:
        mapper : debug

3.3 User entity class

@Data various attribute getters, setters and other methods

@AllArgsConstructor parameterized constructor

@NoArgsConstructor no-argument constructor

package com.bcn.login_mybatis_demo.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author 大白菜
 * @date Created in 2022/9/26 14:56
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    public Integer uid;
    public String uname;
    public String uaccount;
    private String upassword;

    public User(String uname, String uaccount, String upassword) {
        this.uname = uname;
        this.uaccount = uaccount;
        this.upassword = upassword;
    }
}

3.4 UserMapper interface layer

@mapper Mybatis data access layer flag

@Repository SpringBoot data access layer flag

package com.bcn.login_mybatis_demo.mapper;

import com.bcn.login_mybatis_demo.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

/**
 * @author 大白菜
 * @date Created in 2022/9/26 14:56
 */
@Mapper
@Repository
public interface UserMapper {
    User selectUserByUact(String uact);

    String selectUpwdByUact(String uact);

    void insertUser(User user);
}

3.5 UserService business interface layer

When the business requirements are relatively simple, this layer can be discarded and only ServiceImpl can be used.

package com.bcn.login_mybatis_demo.service;

import com.bcn.login_mybatis_demo.pojo.User;

/**
 * @author 大白菜
 * @date Created in 2022/9/26 14:56
 */
public interface UserSerivce {

    public String loginService(String uact, String upwd);

    public String registerService(User user);

}

3.6 UserServiceImpl business layer

@Service business layer flag

package com.bcn.login_mybatis_demo.service.serviceImpl;

import com.bcn.login_mybatis_demo.mapper.UserMapper;
import com.bcn.login_mybatis_demo.pojo.User;
import com.bcn.login_mybatis_demo.service.UserSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 大白菜
 * @date Created in 2022/9/26 14:56
 */
@Service
public class UserServiceImpl implements UserSerivce {
    @Autowired
    UserMapper userMapper;

    @Override
    public String loginService(String uact, String upwd) {
        User user = userMapper.selectUserByUact(uact);
        if (user!=null){
            String userEpwd= user.getUpassword();
            if(upwd.equals(userEpwd)){
                return "SUCCESS";
            }else{
                return "密码错误";
            }
        }
        return "账号错误";
    }


    @Override
    public String registerService(User user) {
        User userE=userMapper.selectUserByUact(user.getUaccount());
        if(userE==null){
            if("".equals(user.getUpassword())){
                return "密码为空";
            }else if("".equals(user.getUname())){
                return "用户昵称为空";
            }else{
                userMapper.insertUser(user);
                return "SUCCESS";
            }
        }else{
            return "此用户已被注册";
        }
    }

}

3.7 UserController control layer

@SuppressWarnings({"all"}) console output filters out warning messages

@RestController control layer flag, equivalent to @Controller+@ResponseBody

@RequestMapping() external interface address

package com.bcn.login_mybatis_demo.controller;

import com.bcn.login_mybatis_demo.pojo.User;
import com.bcn.login_mybatis_demo.service.serviceImpl.UserServiceImpl;
import com.bcn.login_mybatis_demo.util.Result;
import com.bcn.login_mybatis_demo.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 大白菜
 * @date Created in 2022/9/26 14:56
 */
@SuppressWarnings({"all"})
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserServiceImpl userServiceImpl;

    @RequestMapping("/login")
    public Result login(@RequestParam String uact, @RequestParam String upwd) {
        String msg = userServiceImpl.loginService(uact,upwd);
        if(("SUCCESS").equals(msg)){
            return ResultUtil.success("登录成功");
        }else{
            return ResultUtil.error(msg);
        }
    }

    @RequestMapping("/register")
    public Result login(@RequestBody User user) {
        String msg = userServiceImpl.registerService(user);
        if(("SUCCESS").equals(msg)){
            return ResultUtil.success("注册成功");
        }else{
            return ResultUtil.error(msg);
        }
    }

}

3.8 Result, ResultCode, ResultUtil return result tool class

In formal development, in addition to the Body, we also need the status code and status information returned to the front end. This requires the use of the Result tool class. The return effect is as follows: 

Result class

package com.bcn.login_mybatis_demo.util;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author 大白菜
 * @date Created in 2022/9/26 19:54
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> {
    private Integer code;
    private String msg;
    private T data;
}

 ResultCode class

package com.bcn.login_mybatis_demo.util;

/**
 * @author 大白菜
 * @date Created in 2022/9/26 19:50
 */

public enum ResultCode {
    // 自定义枚举内容
    SUCCESS(200, "Success"),

    ERROR(-100, "Error");


    private Integer code;
    private String msg;

    ResultCode(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

}

 ResultUtil class

package com.bcn.login_mybatis_demo.util;

/**
 * @author 大白菜
 * @date Created in 2022/9/26 19:55
 */
public class ResultUtil {
    /**
     * 成功且带数据
     **/
    public static Result success(Object object) {
        Result result = new Result();
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setMsg(ResultCode.SUCCESS.getMsg());
        result.setData(object);
        return result;
    }

    /**
     * 成功但不带数据
     **/
    public static Result success() {

        return success(null);
    }

    /**
     * 失败
     **/
    public static Result error(Object object) {
        Result result = new Result();
        result.setCode(ResultCode.ERROR.getCode());
        result.setMsg(ResultCode.ERROR.getMsg());
        result.setData(object);
        return result;
    }
}

3.9 Mapper.xml mapping file

To use Mybatis, you need to create a mapper folder under resource, which stores various xml mapping files.

<?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.bcn.login_mybatis_demo.mapper.UserMapper">
    <insert id="insertUser">
        insert into user values (null,#{uname},#{uaccount},#{upassword})
    </insert>

    <select id="selectUserByUact" resultType="com.bcn.login_mybatis_demo.pojo.User">
        select * from user where uaccount = #{uact}
    </select>

    <select id="selectUpwdByUact" resultType="java.lang.String">
        select upassword from user where uaccount= #{uact}
    </select>
</mapper>

3.10 login.sql database file

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `uname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `uaccount` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `upassword` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`uid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '皮卡丘', '123456', '123456');
INSERT INTO `user` VALUES (4, '杰尼龟', '1234567', '123456');
INSERT INTO `user` VALUES (7, '妙蛙种子', '12345678', '123456');

SET FOREIGN_KEY_CHECKS = 1;

Guess you like

Origin blog.csdn.net/ccaoshangfei/article/details/127078480