mybatis实现一对多查询代码
时间: 2024-01-01 20:16:57 浏览: 68
假设我们有两个表,一个是订单表(order),另一个是订单详情表(order_item),订单表和订单详情表是一对多的关系(即一个订单可以对应多个订单详情),下面是使用MyBatis实现一对多查询的代码示例。
1. 定义Order类和OrderItem类
```java
public class Order {
private Integer id;
private String orderNo;
private List<OrderItem> orderItemList;
// 省略getter和setter方法
}
public class OrderItem {
private Integer id;
private Integer orderId;
private String productName;
private Integer quantity;
// 省略getter和setter方法
}
```
2. 编写OrderMapper.xml文件
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.dao.OrderMapper">
<!-- 根据订单ID查询订单详情 -->
<select id="findOrderDetailsByOrderId" resultMap="orderResultMap">
SELECT o.*, oi.id AS oi_id, oi.product_name, oi.quantity
FROM `order` o
LEFT JOIN order_item oi ON o.id = oi.order_id
WHERE o.id = #{orderId}
</select>
<resultMap id="orderResultMap" type="com.example.entity.Order">
<!-- 订单信息映射 -->
<id property="id" column="id"/>
<result property="orderNo" column="order_no"/>
<!-- 订单详情映射 -->
<collection property="orderItemList" ofType="com.example.entity.OrderItem">
<id property="id" column="oi_id"/>
<result property="productName" column="product_name"/>
<result property="quantity" column="quantity"/>
</collection>
</resultMap>
</mapper>
```
3. 编写OrderMapper接口
```java
public interface OrderMapper {
List<Order> findOrderDetailsByOrderId(Integer orderId);
}
```
4. 在Spring配置文件中配置OrderMapper
```xml
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.example.entity"/>
<property name="mapperLocations">
<array>
<value>classpath*:mapper/*.xml</value>
</array>
</property>
</bean>
<bean id="orderMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.example.dao.OrderMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
```
5. 调用OrderMapper接口方法进行一对多查询
```java
@Autowired
private OrderMapper orderMapper;
public void testFindOrderDetailsByOrderId() {
Integer orderId = 1;
List<Order> orderList = orderMapper.findOrderDetailsByOrderId(orderId);
for (Order order : orderList) {
System.out.println(order.getOrderNo());
List<OrderItem> orderItemList = order.getOrderItemList();
for (OrderItem orderItem : orderItemList) {
System.out.println(orderItem.getProductName() + ", " + orderItem.getQuantity());
}
}
}
```
通过以上步骤,我们就可以实现使用MyBatis进行一对多查询了。
阅读全文