Mybatis 获取自增ID | Eddie'Blog
Mybatis 获取自增ID

Mybatis 获取自增ID

eddie 398 2020-12-14

目录

Mybatis

例子

    @Transactional(rollbackFor = Exception.class)
    public Integer createOrder() throws Exception {

	// 省略无关代码 ...

	// 插入 order 记录
        Order order = Order.builder()
                .orderAmount(product.getPrice().multiply(new BigDecimal(purchaseProductNum)))
                .orderStatus(1)
                .receiverName("xxx")
                .receiverMobile("13800138000")
                .createTime(new Date())
                .createUser("xxx")
                .updateTime(new Date())
                .updateUser("xxx")
                .build();
        orderMapper.insertSelective(order);

	// 根据上面插入的order记录获取主键ID
        orderItemMapper.insertSelective(OrderItem.builder()
                .orderId(order.getId())
                .productId(product.getId())
                .productPrice(product.getPrice())
                .purchaseNum(purchaseProductNum)
                .createUser("xxx")
                .createTime(new Date())
                .updateUser("xxx")
                .updateTime(new Date())
                .build()
        );

        return order.getId();
    }

}

图片.png

办法一

OrderMapper.xml

  <insert id="insertSelective" parameterType="com.example.distributedemo.model.Order" useGeneratedKeys="true" keyProperty="id">
    <!--
	省略无关代码 ...
    -->
  </insert>

办法二

  <insert id="insertSelective" parameterType="com.example.distributedemo.model.Order">
    <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="id">
        SELECT LAST_INSERT_ID()
    </selectKey>
    <!--
	省略无关代码 ...
    -->
  </insert>

图片.png


# Java # Mybatis