SoFunction
Updated on 2025-04-07

Mybatis-plus example code to implement multi-table query

There are usually several ways to implement multi-table query in MyBatis-Plus:

1. Use annotations for multi-table query

You can use it in the Mapper interface@Select Annotation is used to write SQL query statements to implement multi-table query. For example, if you want to query user information and corresponding area names based on user ID, you can write it like this:

@Mapper
@Repository
public interface UserMapper extends BaseMapper<User> {
    @Select("select user.* ,area.area_name from user,area " +
            "where user.area_id =  and  = #{id}")
    User getUserById(int id);
}

2. Use MyBatis-Plus Join Extension

MyBatis-Plus Join is an extension library that provides the ability to check multiple tables. You can use it by adding dependencies:

<dependency>
    <groupId></groupId>
    <artifactId>mybatis-plus-join</artifactId>
    <version>1.4.5</version>
</dependency>

Then, you can useJoinLambdaQueryWrapperTo construct the conditions for multi-table joint search. For example, query user information for each order:

import ;
import ;
import ;
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    public List&lt;UserOrderDTO&gt; getOrderWithUser() {
        MPJLambdaWrapper&lt;Order&gt; wrapper = new MPJLambdaWrapper&lt;&gt;();
        ()        // Query all fields of the Order table               .select(User::getName)         // Query the Name field of the User table               .leftJoin(, User::getId, Order::getUserId);  // Use left join to connect        return (, wrapper);
    }
}

3. Use XML configuration files to perform multi-table query

Another approach is to define SQL statements for multi-table queries in the XML configuration file of Mapper. For example:

&lt;mapper namespace=""&gt;
    &lt;resultMap  type=""&gt;
        &lt;result property="userName" column="name"/&gt;
        &lt;result property="userAge" column="age"/&gt;
        &lt;!-- Other field mappings --&gt;
    &lt;/resultMap&gt;
    &lt;select  resultMap="orderMap"&gt;
        select o.order_id, o.user_id, o.goods_name, o.goods_price, , 
        from t_order as o left join t_user as u on o.user_id = 
    &lt;/select&gt;
&lt;/mapper&gt;

These methods provide flexible ways to implement multi-table query, and you can choose the appropriate implementation method according to the specific needs of the project.

This is the article about the example code of mybatis-plus implementing multi-table query. For more related contents of mybatis-plus multi-table query, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!