SoFunction
Updated on 2025-03-09

Detailed explanation of the most commonly used operations of MyBatis to add, delete, modify and search

1. Introduction

MyBatis is an excellent persistence layer framework. It connects objects to database operations through SQL mapping, making the mapping between Java objects and database tables clearer. MyBatis defines SQL statements by mapping files and automatically maps the result set to Java objects. It also supports the writing of dynamic SQL, greatly improving the efficiency and flexibility of database operations.

This blog will introduce in detail the most commonly used operations in MyBatis: Add, Delete, Modify, and Check (CRUD). We will use a simpleUserAs an example, use MyBatis to perform basic addition, deletion, modification and search operations.

2. Preparation

Before using MyBatis, we first need to introduce the core dependencies of MyBatis and do some basic configuration.

rely()

<dependency>
    <groupId></groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.10</version> <!-- Choose the version that suits you -->
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.27</version> <!-- Choose the version that suits you -->
</dependency>

Configuration File ()

existsrc/main/resourcesCreated in the directoryFile, basic information used to configure MyBatis.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <environments default="development">
        <environment >
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value=""/>
                <property name="url" value="jdbc:mysql://localhost:3306/your_db"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/example/mapper/"/>
    </mappers>
</configuration>

3. Specific design

1. Database table design

In order to demonstrate the MyBatis addition, deletion, modification and search operations, we need a database table. Here we use a simpleusersurface:

CREATE TABLE user (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(50) NOT NULL
);

2. Mapper interface: UserMapper

CreateUserMapperInterface, defines the method of adding, deleting, modifying and searching.

public interface UserMapper {
    int insertUser(User user);  // Insert the user    int updateUser(User user);  // Update user    int deleteUser(Integer id); // Delete the user    User selectUserById(Integer id); // Query the user by ID    List&lt;User&gt; selectAllUsers(); // Query all users}

3. Mapper mapping file:

existsrc/main/resources/com/example/mapper/Created in the directoryFile and write the corresponding SQL statement.

&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
&lt;mapper namespace=""&gt;

    &lt;!-- Insert the user --&gt;
    &lt;insert  parameterType=""&gt;
        INSERT INTO user (username, password)
        VALUES (#{username}, #{password})
    &lt;/insert&gt;

    &lt;!-- Update users --&gt;
    &lt;update  parameterType=""&gt;
        UPDATE user
        SET username = #{username}, password = #{password}
        WHERE id = #{id}
    &lt;/update&gt;

    &lt;!-- Delete users --&gt;
    &lt;delete  parameterType="int"&gt;
        DELETE FROM user WHERE id = #{id}
    &lt;/delete&gt;

    &lt;!-- according to ID Query user --&gt;
    &lt;select  resultType="" parameterType="int"&gt;
        SELECT id, username, password FROM user WHERE id = #{id}
    &lt;/select&gt;

    &lt;!-- Query all users --&gt;
    &lt;select  resultType=""&gt;
        SELECT id, username, password FROM user
    &lt;/select&gt;

&lt;/mapper&gt;

4. MyBatis adds, deletes, modify and check operations

1. Insert data (Insert)

Insert data to useinsertTags and passinsertUserMethod execution.

public class UserService {
    private SqlSession sqlSession;

    public int addUser(User user) {
        UserMapper userMapper = ();
        return (user);
    }
}

User user = new User();
("john");
("password");
(user);

2. Update data (Update)

Update data usageupdateTags, byupdateUserMethod execution.

public int updateUser(User user) {
    UserMapper userMapper = ();
    return (user);
}

User user = new User();
(1);
("john_updated");
("newpassword");
(user);

3. Delete data (Delete)

Use Delete DatadeleteTags, bydeleteUserMethod execution.

public int deleteUser(int id) {
    UserMapper userMapper = ();
    return (id);
}

(1);

4. Query data (Select)

Query data useselectTags, commonly used to query and query all data based on ID.

public User getUserById(int id) {
    UserMapper userMapper = ();
    return (id);
}

Query all users:

public List<User> getAllUsers() {
    UserMapper userMapper = ();
    return ();
}

User user = (1);
List<User> users = ();

5. Summary

This article introduces the common addition, deletion, modification and search operations in MyBatis. By creating database tables, entity classes, Mapper interfaces and mapping files, we have achieved theuserThe operation of adding, deleting, modifying and checking tables. MyBatis simplifies database operations and allows developers to focus on the implementation of business logic through mapping files and interfaces.

In actual development, MyBatis also provides rich functions, such as dynamic SQL, paging plug-ins, etc., which can help developers deal with more complex business needs. In the next blog, we will dive into dynamic SQL and common SQL injection prevention tips in MyBatis.

This is the article about MyBatis' most commonly used addition, deletion, modification and search operations. For more information about MyBatis's addition, deletion, modification and search operations, please search for my previous articles or continue to browse the related articles below. I hope everyone will support me in the future!