mybatisplus一对多查询
时间: 2023-09-19 18:07:38 浏览: 136
MybatisPlus 多租户架构(Multi-tenancy)实现详解
MyBatis Plus provides convenient methods for performing one-to-many queries. To perform a one-to-many query using MyBatis Plus, you can follow these steps:
1. Define the corresponding entity classes for your tables. Let's say you have two tables: "User" and "Order". The "User" table has a primary key "id", and the "Order" table has a foreign key "user_id" referencing the "id" column in the "User" table.
```java
@Data
public class User {
private Long id;
private String name;
// other fields and getters/setters
}
@Data
public class Order {
private Long id;
private String orderNo;
private Long userId;
// other fields and getters/setters
}
```
2. Define the mapper interfaces for the entities. Create two mapper interfaces: "UserMapper" and "OrderMapper".
```java
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
@Mapper
public interface OrderMapper extends BaseMapper<Order> {
}
```
3. Configure the mapping relationship between the entities in the XML mapper files. In the XML mapper file of the "Order" entity, define a result map to map the "User" entity.
```xml
<resultMap id="orderResultMap" type="com.example.Order">
<id property="id" column="id"/>
<result property="orderNo" column="order_no"/>
<result property="userId" column="user_id"/>
<association property="user" javaType="com.example.User">
<id property="id" column="user_id"/>
<result property="name" column="user_name"/>
<!-- other user fields -->
</association>
</resultMap>
```
4. Use the MyBatis Plus query methods to perform the one-to-many query. You can use the `selectList` method of the "OrderMapper" to retrieve the orders along with their associated users.
```java
@Autowired
private OrderMapper orderMapper;
public List<Order> getOrdersWithUsers() {
return orderMapper.selectList(null);
}
```
This will fetch a list of orders from the "Order" table, and each order object will have the associated user object populated based on the mapping defined in the XML mapper file.
Please note that you may need to adjust the code according to your specific database structure and naming conventions.
阅读全文