014.selectKey与useGeneratedKeys的区别

1.selectKey与useGeneratedKeys的区别

 

 

 

 

 

 

 

 

 

 2.代码示例

 <!--selectKey与useGeneratedKeys的区别-->
    <!--selectKey用法-->
    <!--<insert id="insert" parameterType="com.imooc.mybatis.entity.Goods" >-->
    <!--    &lt;!&ndash;不用添加主键,主键是自动生成的编号  selectkey&ndash;&gt;-->
    <!--    INSERT INTO t_goods(title, sub_title, original_cost, current_price, discount, is_free_delivery, category_id)-->
    <!--    VALUES (#{title} , #{subTitle} , #{originalCost}, #{currentPrice}, #{discount}, #{isFreeDelivery}, #{categoryId})-->
    <!--    <selectKey resultType="Integer" keyProperty="goodsId" order="AFTER">-->
    <!--    select last_insert_id()-->
    <!--    </selectKey>-->
    <!--</insert>-->

    <!--useGeneratedKeys用法-->
    <insert id="insert" parameterType="com.imooc.mybatis.entity.Goods" useGeneratedKeys="true" keyProperty="goodsId" keyColumn="goods_id">
        <!--不用添加主键,主键是自动生成的编号  selectkey-->
        INSERT INTO t_goods(title, sub_title, original_cost, current_price, discount, is_free_delivery, category_id)
        VALUES (#{title} , #{subTitle} , #{originalCost}, #{currentPrice}, #{discount}, #{isFreeDelivery}, #{categoryId})
    </insert>
/**
     * 新增数据
     * @throws Exception
     */
    @Test
    public void testInsert() throws Exception {
        SqlSession session = null;
        try{
            session = MyBatisUtils.openSession();
            Goods goods = new Goods();
            goods.setTitle("测试商品");
            goods.setSubTitle("测试子标题");
            goods.setOriginalCost(200f);
            goods.setCurrentPrice(100f);
            goods.setDiscount(0.5f);
            goods.setIsFreeDelivery(1);
            goods.setCategoryId(43);
            //insert()方法返回值代表本次成功插入的记录总数
            int num = session.insert("goods.insert", goods);
            session.commit();//提交事务数据
            System.out.println(goods.getGoodsId());
        }catch (Exception e){
            if(session != null){
                session.rollback();//回滚事务
            }
            throw e;
        }finally {
            MyBatisUtils.closeSession(session);
        }
    }

 

posted @ 2022-11-07 22:57  李林林  阅读(179)  评论(0编辑  收藏  举报