mybatis 插入,更新,修改数据

<!-- 插入操作 -->
<!--selectKey 进行主键回添
    order:执行顺序
    last_insert_id():MySql自带的函数,用于获得当前连接最后的产生的id
-->
<insert id="insertadd" parameterType="com.lx.entity.Goods">
   insert into t_goods(title, sub_title, original_cost, current_price, discount, 
   is_free_delivery, category_id)
   value (#{title},#{subTitle},#{originalCost},#{currentPrice},#{discount},# 
   {isFreeDelivery},#{categoryId})
   <selectKey resultType="Integer" keyProperty="goodsId" order="AFTER">
        select last_insert_id()
   </selectKey>
</insert>

 

/**
  * 插入
  */
@Test
public void insertadd(){
   SqlSession sqlsession = null;
   try {
       sqlsession = JdbcUtil.getSqlSession();
       Goods goods = new Goods("测试商品", "子标题", 200f, 100f, 0.5f, 1, 43);
       // insert()方法返回值代表本次成功插入的记录总数
       int num = sqlsession.insert("goods.insertadd", goods);
       // 提交事务
       sqlsession.commit();
       System.out.println(goods.getGoodsId());
  }catch (Exception e){
       if(sqlsession != null){
       // 回滚事务
       sqlsession.rollback();
  }
       e.printStackTrace();
  }finally {
       JdbcUtil.getClose(sqlsession);
    }
}

 

更新数据

<update id="updateGoods" parameterType="com.lx.entity.Goods">
    update t_goods
    set
    title = #{title},
    sub_title = #{subTitle},
    original_cost = #{originalCost},
    current_price = #{currentPrice},
    discount = #{discount},
    is_free_delivery = #{isFreeDelivery},
    category_id = #{categoryId}
    where
    goods_id = #{goodsId}
</update>

 

/**
 * 更新操作
 */
@Test
public void testUpdate(){
     SqlSession session = null;
     try{
        session = JdbcUtil.getSqlSession();
        Goods goods = session.selectOne("goods.findOne", 739);
        goods.setTitle("测试标题");
        int num = session.update("goods.updateGoods", goods);
        session.commit();
     }catch (Exception e){
        if(session!=null){
           session.rollback();
     }
        e.printStackTrace();
     } finally {
        JdbcUtil.getClose(session);
     }
}

 

删除数据

<delete id="deleteMsg" parameterType="Integer">
    delete from t_goods where goods_id = #{value}
</delete>

@Test
public void deleteOne(){
    SqlSession session = null;
    try{
       session =JdbcUtil.getSqlSession();
       int num = session.delete("goods.deleteMsg", 740);
       session.commit();
       System.out.println(num);
    }catch (Exception e){
       if(session!=null){
          session.rollback();
    }
        e.printStackTrace();
    } finally {
        JdbcUtil.getClose(session);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值