MaBatis:数据插入,修改,删除
Mapper XML
<insert id="insert" parameterType="com.MyBatis.entity.Goods">
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>
<update id="update" parameterType="com.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>
<delete id="delete" parameterType="Integer">
delete from t_goods where goods_id = #{value}
</delete>
测试代码
@Test
public void testInsert(){
SqlSession sqlSession=null;
try{
sqlSession=MyBatisUtils.openSession();
Goods goods = new Goods();
goods.setTitle("aaa");
goods.setSubTitle("bbb");
goods.setOriginalCost(200f);
goods.setCurrentPrice(100f);
goods.setDiscount(0.5f);
goods.setIsFreeDelivery(1);
goods.setCategoryId(43);
//insert方法返回值代表本次成功插入的记录总数
int insert = sqlSession.insert("goods.insert", goods);
sqlSession.commit();//提交事务数据
System.out.println(goods.getGoodsId());
}catch (Exception e){
if(sqlSession!=null){
sqlSession.rollback();//回滚事务
}
throw e;
}finally {
MyBatisUtils.closeSession(sqlSession);
}
}
@Test
public void testUpdate(){
SqlSession sqlSession=null;
try{
sqlSession=MyBatisUtils.openSession();
Goods goods = sqlSession.selectOne("goods.selectById",741);
goods.setTitle("更新测试商品");
goods.setSubTitle("更新副标题");
int num = sqlSession.update("goods.update", goods);
sqlSession.commit();
}catch (Exception e){
if(sqlSession!=null){
sqlSession.rollback();//回滚事务
}
throw e;
}finally {
MyBatisUtils.closeSession(sqlSession);
}
}
@Test
public void testDelete(){
SqlSession sqlSession=null;
try{
sqlSession=MyBatisUtils.openSession();
int num=sqlSession.delete("goods.delete",739);
sqlSession.commit();
}catch (Exception e){
if(sqlSession!=null){
sqlSession.rollback();//回滚事务
}
throw e;
}finally {
MyBatisUtils.closeSession(sqlSession);
}
}

浙公网安备 33010602011771号