Easy to understand: MyBatis usage and best practices

Add MyBatis framework support

When creating a new MyBatis and Spring Boot project, add
the following references:
insert image description here

Configure connection string and MyBatis

Configure the connection string

Add the following to application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/demo?characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=666666
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Configure the XML path in MyBatis

Still add the following content in application.properties:

mybatis.mapper-locations=classpath:mapper/*Mapper.xml
# 配置mybatis xml 的⽂件路径,在 resources/mapper 创建所有表的 xml ⽂件

insert image description here

Add business code

According to the back-end development idea, perform mybatis query user function, the flow chart is as follows:
insert image description here

Create database and tables

Create a demo database

drop database if exists demo;
create database demo default character set utf8mb4;

use database

use demo;

create student table

drop table if exists stu;
create  table stu(
    id int primary key auto_increment,
    name varchar(100) not null ,
    sex  varchar(10) not null

) default charset 'utf8mb4';

Add student information

insert into  demo.stu(id,name,sex) values (1,'zcx','男');

Add user entity class

import lombok.Data;
@Data
public class User {
    
    
    private Integer id;
    private String name;
    private String sex;
}

Add mapper interface

import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
    
    
public List<User> getAll();
}

Add UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybati
s.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mybatisdemo.dao.UserMapper">
   
</mapper>
  • Mapper tag: The namespace attribute needs to be specified to indicate the namespace, and what needs to be written is the fully qualified name of the Mapper interface (including the package path). The role of namespace is to specify the Mapper interface corresponding to the Mapper XML file and establish the mapping relationship between the two.
    insert image description here
    Subsequent sql operation tags can be written in the Mapper tag
    For example:
    add query operations
 <select id="getAll">
        select * from stu
    </select>

Add Service layer

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserService {
    
    
    @Resource
    private UserMapper userMapper;
    public List<User> getAll() {
    
    
        return userMapper.getAll();
    }

}

Add Controller layer

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/u")
public class UserController {
    
    
    @Resource
    private UserService userService;
    @RequestMapping("/getall")
    public List<User> getAll(){
    
    
        return userService.getAll();
    }
}

Query access using a browser
insert image description here

CRUD operation

The operations of adding, deleting and modifying users correspond to the following tags using MyBatis:

  • <insert>Labels: insert statement
  • <update>Tags: modify statement
  • <delete>Labels: delete statement

Add operation

Controller implementation code:

 @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Integer add(@RequestBody User user){
    
    
        return userService.add(user);
    }

Service implementation code:

  public Integer add(User user ){
    
    
        return userMapper.add(user);
    }

mapper interface:

Integer add(User user);

mapper.xml:

<insert id="add" >
        insert into stu(name,sex)
        values(#{
    
    name},#{
    
    sex})
    </insert>

Use Postman to add access:
insert image description here
You can also return the auto-increment primary key, modify the following code:

 @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Integer add(@RequestBody User user){
    
    
        userService.add(user);
        return user.getId();
    }
<insert id="add" useGeneratedKeys="true" keyProperty="id">
        insert into stu(name,sex)
        values(#{
    
    name},#{
    
    sex})
    </insert>

insert image description here
insert image description here

  • useGeneratedKeys: This will make MyBatis use JDBC's getGeneratedKeys method to retrieve the primary key generated internally by the database, the default is false
  • keyProperty: Specifies the property that can uniquely identify the object. MyBatis will use the return value of getGeneratedKeys or the selectKey subelement of the insert statement to set its value

delete operation

Modify the controller:

 @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Integer update( Integer id,  String name) {
    
    
        return userService.update(id, name);
    }

mapper.xml:

<update id="update">
        update stu set name=#{
    
    name} where id=#{
    
    id}
    </update>

Other code modifications are similar to adding operations
insert image description here
Check the database and find that the modification is successful
insert image description here

modify operation

Modify the controller:

@RequestMapping("/delById")
    public Integer delById( Integer id){
    
    
        return userService.delById(id);
    }

mapper.xml:

  <delete id="delById" parameterType="java.lang.Integer">
        delete from stu where id=#{
    
    id}
    </delete>

insert image description here
Check the database, delete successfully
insert image description here

Guess you like

Origin blog.csdn.net/st200112266/article/details/132235916