1. 程式人生 > 其它 >011.更新與刪除操作

011.更新與刪除操作

1.資料的更新

1.1 goods.xml

    <update id="update" parameterType="com.imooc.mybatis.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>

1.2 測試用例

  /**
     * 更新資料
     *
     * @throws Exception
     */
    @Test
    public void testUpdate() throws Exception
    {
        SqlSession session = null;
        try
        {
            session = MyBatisUtils.openSession();
            Goods goods = session.selectOne("goods.selectById", 740);
            goods.setTitle(
"更新測試商品123"); int num = session.update("goods.update", goods); session.commit();//提交事務資料 } catch (Exception e) { if (session != null) { session.rollback();//回滾事務 } throw e; } finally
{ MyBatisUtils.closeSession(session); } }

2.刪除

2.1 goods.xml

 <!--delete from t_goods where goods_id in (1920,1921)-->
    <delete id="delete" parameterType="Integer">
        delete from t_goods where goods_id = #{value}
    </delete>

2.2 測試用例

  /**
     * 刪除資料
     *
     * @throws Exception
     */
    @Test
    public void testDelete() throws Exception
    {
        SqlSession session = null;
        try
        {
            session = MyBatisUtils.openSession();
            int num = session.delete("goods.delete", 740);
            session.commit();//提交事務資料
        }
        catch (Exception e)
        {
            if (session != null)
            {
                session.rollback();//回滾事務
            }
            throw e;
        }
        finally
        {
            MyBatisUtils.closeSession(session);
        }
    }