Teach you how to use the MyBatis framework step by step

Table of contents

What is MyBatis?

Configure MyBatis development environment

Method 1: Add dependencies when creating the project

Method 2: Add dependencies after creating the project

Configure connection string

Configure XML path in MyBatis

Business code

Add entity class

AddService

AddController

Add, delete and modify operations

Add user actions

Modify user operations

Delete user action

Parameter placeholders #{} and ${}

like query (fuzzy matching)

Multi-table query

In the next issue, we will continue to learn more about the mybatis framework. If you like it, please follow me~


What is MyBatis?

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures and advanced mapping. MyBatis removes almost all 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) into records in the database through simple XML or annotations. 

In one sentence, MyBatis is a tool that makes it easier to interact with programs and databases.

Configure MyBatis development environment

Method 1: Add dependencies when creating the project

First we create a new project, as shown below:

 Then click next

Finally we created a project

What should I do if I have created a project and want to add mybatis dependencies?

Don't worry, we still have plan B

Method 2: Add dependencies after creating the project

We first download EditStarters  in the plug-in (settings)  , as shown in the figure below:

How to use the EditStarters plug-in: 

Click on the blue box: 

 Just search for "MyBatis" and add:

Configure connection string

Add the following content to application.yml:

# 数据库连接配置
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mycnblog?characterEncoding=utf8&useSSL=false
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

Configure XML path in MyBatis

The XML of MyBatis stores the specific operation SQL for querying the database. The configuration is as follows:

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

Place this code below the configuration connection string

Business code

Add entity class

First add the user's entity class:

import lombok.Data;
import java.util.Date;
@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    private String photo;
    private Date createTime;
    private Date updateTime;
}

Add mapper interface:

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

Add UserMapper.xml:

Build a package here and create an xml file:

The implementation of data persistence, the fixed xml format of mybatis:

<?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.mybatisdemo1.mapper.UserMapper">
    
</mapper>

Add sql statement in xml file

<?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.mybatisdemo1.mapper.UserMapper">
    <select id="getAll" resultType="com.example.mybatisdemo1.entity.User">
        select * from userinfo
    </select>
</mapper>

Mapper tag: You need to specify the namespace attribute, which represents the namespace. The value is the fully qualified name of the mapper interface, including the full package name and class name.

Query tag: used to perform database query operations

id: It is the same as the method name defined in Interface, indicating the specific implementation method of the interface.

resultType: is the returned data type, which is the entity class we defined at the beginning.

AddService

The service layer implementation code is as follows:

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();
       }
}

AddController

The implementation code of the controller layer is as follows:

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();
    }
}

After the above code is written, the entire MyBatis query function has been implemented. Next, use postman to test it.

Add, delete and modify operations

Let's implement the operations of adding, deleting and modifying users. The corresponding MyBatis tags are as follows:

<insert> tag: insert statement

<update> tag: modify statement

<delete> tag: delete statement

Add user actions

Controller implementation code:

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

Add an abstract method to the mapper interface:

Integer add(User user);

Add sql statements in mapper.xml

<insert id="add">
 insert into userinfo(username,password,photo,state)
 values(#{username},#{password},#{photo},1)
</insert>

Add a json format data in postman:

By default, the number of affected rows is returned 

Special addition: return auto-increment id

Controller implementation code:

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

Add the add2() method in usermapper:

Integer add2(User user);

mapper.xml implements the following sql statement:

<!-- 返回⾃增id -->
    <insert id="add2" useGeneratedKeys="true" keyProperty="id">
        insert into userinfo(username,password,photo,state)
        values(#{username},#{password},#{photo},1)
    </insert>

useGeneratedKeys: This will cause MyBatis to use JDBC's getGeneratedKeys method to retrieve the primary key generated internally by the database. The default value is false.

keyColumn: Set the column name of the generated key value in the table

keyProperty: Specifies the property that can uniquely identify the object. MyBatis will use the return value of getGeneratedKeys or the selectKey sub-element of the insert statement to set its value. Default value: unset. If there is more than one generated column, multiple attribute names can be separated by commas.

Use postman to return results:

Modify user operations

Controller adds a method to change password: 

@RequestMapping("/updatePassword")
    public int update(Integer id, String password, String newPassword) {
        return userService.updatePassword(id,password,newPassword);
    }

Define an update method in the usermapper interface:

Integer updatePassword(Integer id, String password,String newPassword);

Server service code:

public Integer updatePassword(Integer id, String password, String newPassword){
              return userMapper.updatePassword(id,password,newPassword);
       }

mapper.xml implementation code (the password can only be changed if the original password and ID are correct):

<update id="updatePassword" >
        update userinfo set password=#{newPassword} where id=#{id} and password=#{password}
    </update>

Test with postman:

 

 Note: Returning 1 means that the number of affected rows is 1

Delete user action

Controller adds and deletes methods:

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

 Define an update method in the usermapper interface:

Integer delById(Integer id);

Server service code:

public Integer delById(Integer id){
              return userMapper.delById(id);
       }

 mapper.xml implementation code:

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

Test with postman:

 

Parameter placeholders #{} and ${}

#{}: Precompilation processing.

${}: Direct replacement of characters.

Precompilation processing means: when MyBatis processes #{}, it will replace #{} in SQL with ? and use the set method of PreparedStatement to assign values. Direct replacement: When MyBatis processes ${}, it replaces ${} with the value of the variable.

like query (fuzzy matching)

You cannot use ${} directly. You can use mysql's built-in function concat() to handle it. The implementation code is as follows:

<select id="findUserByName3" resultType="com.example.demo.model.User">
     select * from userinfo where username like concat('%',#{username},'%');
</select>

Multi-table query

If the number of rows affected by the return search is added, deleted, or modified, the return type does not need to be set in mapper.xml.

However, even if you query the user's name in the simplest way, you must set the return type, otherwise an error will be reported.

At least two attributes are required for query tags:

id attribute: used to identify the method in the implementation interface;

Result mapping properties: There are two implementation tags for result mapping: <resultMap> and <resultType>.

As shown below:

In the next issue, we will continue to learn more about the mybatis framework. If you like it, please follow me~

おすすめ

転載: blog.csdn.net/m0_62468521/article/details/131401944
おすすめ