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 useJoinLambdaQueryWrapper
To 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<UserOrderDTO> getOrderWithUser() { MPJLambdaWrapper<Order> wrapper = new MPJLambdaWrapper<>(); () // 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:
<mapper namespace=""> <resultMap type=""> <result property="userName" column="name"/> <result property="userAge" column="age"/> <!-- Other field mappings --> </resultMap> <select resultMap="orderMap"> 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 = </select> </mapper>
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!