Springboot mybatis simple quick start example

Time:2022-6-17

1、 Introduction to mybatis

Mybatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. Mybatis eliminates almost all the JDBC code and the work of setting parameters and getting result sets. Mybatis can configure and map primitive types, interfaces and Java POJOs (plain old Java objects) to records in the database through simple XML or annotations.

2、 Mybatis usage steps

1. Overall directory structure of mybatis project

在这里插入图片描述

2. Create a simple springboot project

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3. Add mybatis dependency


  <!--MyBatis-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

在这里插入图片描述

4. Create user table in database

在这里插入图片描述

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Username` varchar (20) not null default '' comment 'username',
  `Password` varchar (50) not null default '' comment 'password',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;

5. In application Properties configure database connection information

#Database related configuration
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useSSL=false&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=Asia/Shanghai&useAffectedRows=true
spring.datasource.username=root
spring.datasource.password=QQ796413

#Mybaits configuration
#Mapper load path
mybatis.mapper-locations= classpath:mapper/*.xml
#Physical package location
mybatis.type-aliases-package= com.example.mybatisdemo.entity
#Myatbis profile
mybatis.config-location= classpath:mybatis-config.xml

6. Create the entity class corresponding to the user table

在这里插入图片描述


package com.example.mybatisdemo.entity;

public class User {
    private int id;
    private String username;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int 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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

7. Create usermapper in mapper/usermapper java

在这里插入图片描述


package com.example.mybatisdemo.mapper;

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

@Mapper
public interface UserMapper{

     User findUserById(Integer id);
}

8. Create a new userservice in service/userservice java

在这里插入图片描述


package com.example.mybatisdemo.service;

import com.example.mybatisdemo.entity.User;

public interface UserService {
    User findUserById(Integer id);
}

9. Create userserviceimpl in service/impl/userserviceimpl java

在这里插入图片描述


package com.example.mybatisdemo.service.impl;

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

@Service
public class UserServiceImpl implements UserService {
        @Autowired
        private UserMapper userMapper;

        @Override
        public User findUserById(Integer id) {
            return userMapper.findUserById(id);
        }
}

10. Create mybatis-conf.xml under Resources

在这里插入图片描述

<?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>
    <settings>
        <!-- Open log -- >
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!-- Open hump nomenclature -- >
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Enable global deferred load -- >
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--  Force an empty collection instance instead of null when the collection is empty -- >
        <setting name="returnInstanceForEmptyRow" value="true"/>
        <!--  Keep key when value in the result set is empty -- >
        <setting name="callSettersOnNulls" value="true"/>
    </settings>
</configuration>

11. Create usermapper xml

在这里插入图片描述

<?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">
<!-- Note: 1 The namespace here is the location of your usermapper -- >
<mapper namespace="com.example.mybatisdemo.mapper.UserMapper">
    <!-- Note the return type here -- >
    <resultMap type="com.example.mybatisdemo.entity.User">
        <result column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
    </resultMap>

    <!-- 2. The ID is the same as your method name, and the resultmap is consistent with the above ID name -- >
    <select resultMap="BaseResultMap">
        select
             id,
             username,
             password
        from
             user
        where
             id= #{id,jdbcType=INTEGER}
    </select>
</mapper>

12. Create usercontroller java

在这里插入图片描述


package com.example.mybatisdemo.controller;

import com.example.mybatisdemo.entity.User;
import com.example.mybatisdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/findUserById")
    public User findUserById(@RequestParam Integer id){
       return userService.findUserById(1);
    }
}

13. Testing

在这里插入图片描述

The project can be downloaded from my resources

This is the end of this article about springboot mybatis quick start – simple examples. For more information about springboot mybatis, please search the previous articles of developeppaer or continue to browse the related articles below. I hope you will support developeppaer in the future!