mybatis批量一对多插入
时间: 2023-11-07 22:49:09 浏览: 218
mybatis-generator,一对一,一对多,批量更新插入2
4星 · 用户满意度95%
MyBatis 的批量插入可以使用 `foreach` 标签,而一对多插入可以通过嵌套查询实现,具体步骤如下:
1. 在 mapper 文件中定义插入语句,例如:
```xml
<insert id="insertOrders" parameterType="java.util.List">
insert into orders (order_no, user_id) values
<foreach collection="list" item="order" separator=",">
(#{order.orderNo}, #{order.userId})
</foreach>
</insert>
```
2. 在 mapper 文件中定义嵌套查询语句,例如:
```xml
<select id="selectOrderItemsByOrderId" resultType="OrderItem">
select * from order_items where order_id = #{orderId}
</select>
```
3. 在 mapper 文件中定义插入 OrderItem 的语句,例如:
```xml
<insert id="insertOrderItems" parameterType="java.util.List">
insert into order_items (order_id, product_id, quantity) values
<foreach collection="list" item="orderItem" separator=",">
(#{orderItem.orderId}, #{orderItem.productId}, #{orderItem.quantity})
</foreach>
</insert>
```
4. 在 Java 代码中,先插入 Orders,然后根据插入的 OrderId 查询对应的 OrderItems,最后批量插入 OrderItems,代码示例如下:
```java
public void insertOrdersAndOrderItems(List<Order> orders) {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
OrderItemMapper orderItemMapper = sqlSession.getMapper(OrderItemMapper.class);
for (Order order : orders) {
orderMapper.insertOrder(order);
List<OrderItem> orderItems = orderItemMapper.selectOrderItemsByOrderId(order.getId());
orderItemMapper.insertOrderItems(orderItems);
}
sqlSession.commit();
}
}
```
阅读全文