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);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!