SoFunction
Updated on 2025-04-06

Use of mybatis map table structure

1. Overview of MyBatis table structure mapping

In MyBatis, the core of table structure mapping is to map tables and fields in the database to Java classes and properties. MyBatis provides flexible configurations, making this mapping very easy to implement. Through mapping, developers can use Java objects to represent data in the database, greatly simplifying the complexity of data operations.

2. Two ways to map table structure of MyBatis

1. XML mapping method

XML mapping is the traditional configuration method of MyBatis, and it is also one of the most flexible and commonly used methods. In this way, the developer needs to write an XML configuration file that specifies the mapping relationship between the database table and the Java class.

Step 1: Create a Java class

Suppose we have oneUserThe table, structure is as follows:

CREATE TABLE User (
    id INT PRIMARY KEY,
    username VARCHAR(50),
    password VARCHAR(50),
    email VARCHAR(50)
);

We can create a corresponding Java class:

public class User {
    private Integer id;
    private String username;
    private String password;
    private String email;

    // Getters and Setters
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
         = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
         = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
         = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
         = email;
    }
}

Step 2: Write an XML mapping file

Next, we need to write an XML file that willUserThe column map of the table toUseron the attributes of the class. The mapping files in MyBatis are usually.xmlis the suffix and placed inresourcesIn the directory.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-////DTD Mapper 3.0//EN"
  "/dtd/">

<mapper namespace="">
    <resultMap  type="">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="email" property="email"/>
    </resultMap>

    <select  resultMap="userResultMap">
        SELECT * FROM User WHERE id = #{id}
    </select>
</mapper>

In this XML file:

  • namespace: Defines the namespace of the mapping file, usually the fully qualified name of the corresponding Mapper interface.
  • resultMap: Defines the mapping relationship between database table columns and Java class attributes.idTags represent primary keys,resultTags represent mappings of ordinary columns.
  • select: Defines an SQL query statement.resultMapThe attribute specifies the mapping relationship of the query results.

Step 3: Create a Mapper Interface

We also need to create a Mapper interface that is associated with the above XML file:

package ;

import ;
import ;

public interface UserMapper {
    User selectUserById(Integer id);
}

Methods declared in interfaces and XMLidConsistent, MyBatis will automatically bind SQL statements to this method.

2. Annotation mapping method

MyBatis also supports mapping table structures through annotations, which is relatively concise and suitable for simple mapping needs.

Step 1: Create a Java class

Like XML mapping, we first need to create a Java class:

public class User {
    private Integer id;
    private String username;
    private String password;
    private String email;

    // Getters and Setters
}

Step 2: Mapping with annotations

We can use annotations in the Mapper interface to complete the mapping:

package ;

import ;
import .*;

public interface UserMapper {

    @Select("SELECT * FROM User WHERE id = #{id}")
    @Results(id = "userResultMap", value = {
        @Result(property = "id", column = "id", id = true),
        @Result(property = "username", column = "username"),
        @Result(property = "password", column = "password"),
        @Result(property = "email", column = "email")
    })
    User selectUserById(Integer id);
}

In the annotation map:

  • @Select: Used to define SQL query statements.
  • @Results: Used to specify the mapping relationship of the query result.
  • @Result: Used to map database table columns to Java class attributes.

3. Advanced features of MyBatis mapping

1. Automatic mapping

MyBatis provides automatic mapping function, that is, when the column name of the table is consistent with the attribute name of the Java class, MyBatis can automatically map the query results to the corresponding Java object without manual configuration.resultMapor@Results. This automatic mapping can simplify development efforts and reduce configuration file complexity.

// Automatic mapping example@Select("SELECT * FROM User WHERE id = #{id}")
User selectUserById(Integer id);

In this example, ifUserThe column names of the table andUserThe attribute names of the class are the same, and MyBatis will automatically complete the mapping.

2. Delay loading

MyBatis supports Lazy Loading, which means that when the query results contain associated objects, you can choose to load them when accessing them.

<resultMap  type="">
    <id column="id" property="id"/>
    <result column="username" property="username"/>
    <result column="password" property="password"/>
    <result column="email" property="email"/>
    <association property="address" javaType=""
                 select=""
                 column="id"/>
</resultMap>

In this example, when accessingUserThe object'saddressMyBatis will delay loading when attributes areAddressObject.

3. Multi-table association query

MyBatis can handle multi-table association queries and map results to multiple Java objects. This usually passesresultMapNested structure or@ResultsNested annotation implementation.

<resultMap  type="">
    <id column="id" property="id"/>
    <result column="username" property="username"/>
    <result column="password" property="password"/>
    <result column="email" property="email"/>
    <association property="department" javaType="">
        <id column="department_id" property="id"/>
        <result column="department_name" property="name"/>
    </association>
</resultMap>

In this example,UserObject andDepartmentThere is an association relationship in the object, and MyBatis will map the results of the association query toUserandDepartmentIn the object.

4. Summary

MyBatis implements the mapping of database table structure and Java objects through XML configuration and annotation, allowing developers to perform database operations more conveniently. XML configuration provides greater flexibility and maintainability, while annotation is more concise and intuitive, suitable for simple scenarios. By rationally using MyBatis's automatic mapping, delayed loading and multi-table association query functions, developers can greatly improve development efficiency, simplify code structure, and focus more on the implementation of business logic.

As a lightweight ORM framework, MyBatis has a mapping function that is not as powerful as Hibernate, but it is more flexible and can better adapt to complex and changeable database operation needs. Mastering the mapping mechanism of MyBatis is an important step to becoming an excellent Java developer.

This is the end of this article about the use of mybatis mapping table structure. For more related contents of mybatis mapping table structure, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!