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);
    }
}

猜你喜欢

转载自blog.csdn.net/whb008/article/details/107506887