基于Maven工程下的MyBatis基本使用之数据插入【回填】、修改与删除

执键写春秋
• 阅读 1892

MyBatis基本使用

声明:基于《基于Maven工程下的MyBatis框架+MySQL+连接池的数据查询操作》与《基于Maven工程下的MyBatis基本使用之SQL传单/多参、多表关联查询》进一步拓展,相关配置文件、数据文件可阅以上两篇。

数据插入,使用进行回填自动生成主键值

<!--需要明确编写获取最新主键的SQL语句-->
<insert id="insert" parameterType="com.imooc.mybatis.entity.Goods" flushCache="true">
    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用来回填自动生成的主键属性,last_insert_id()函数用于获取当前连接最后产生的主键ID-->
        <selectKey resultType="Integer" keyProperty="goodsId" order="AFTER">
            select last_insert_id()
        </selectKey>
    </insert>
@Test
    public void testInsert() throws Exception {
        SqlSession session = null;
        try{
            session = MyBatisUtils.openSession();
            Goods goods = new Goods();
            goods.setTitle("测试插入商品");
            goods.setSubTitle("测试子标题");
            goods.setOriginalCost(200f);
            goods.setCurrentPrice(100f);
            goods.setDiscount(0.5f);
            goods.setIsFreeDelivery(1);
            goods.setCategoryId(43);
            //insert()方法返回值代表本次成功插入的记录总数
            int num = session.insert("goods.insert", goods);
            session.commit();//提交事务数据
            System.out.println(goods.getGoodsId());
        }catch (Exception e){
            if(session != null){
                session.rollback();//回滚事务
            }
            throw e;
        }finally {
            MyBatisUtils.closeSession(session);
        }
    }

数据插入,使用useGeneratedKeys属性进行回填自动生成主键值

这里只需要修改元素:

<!--根据驱动生成对应SQL语句-->
 <insert id="insertII" parameterType="com.imooc.mybatis.entity.Goods"
            useGeneratedKeys="true" keyProperty="goodsId" keyColumn="goods_id">
        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})
    </insert>

数据更新

<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>
@Test
    public void testUpdate() throws Exception {
        SqlSession session = null;
        try{
            session = MyBatisUtils.openSession();
            Goods goods = session.selectOne("goods.selectById", 739);
            goods.setTitle("更新测试商品");
            int num = session.update("goods.update" , goods);
            session.commit();//提交事务数据
        }catch (Exception e){
            if(session != null){
                session.rollback();//回滚事务
            }
            throw e;
        }finally {
            MyBatisUtils.closeSession(session);
        }
    }

数据删除

<!--根据主键删除-->
<delete id="delete" parameterType="Integer">
        delete from t_goods where goods_id = #{value} 
</delete>
@Test
    public void testDelete() throws Exception {
        SqlSession session = null;
        try{
            session = MyBatisUtils.openSession();
            int num = session.delete("goods.delete" , 739);
            session.commit();//提交事务数据
        }catch (Exception e){
            if(session != null){
                session.rollback();//回滚事务
            }
            throw e;
        }finally {
            MyBatisUtils.closeSession(session);
        }
    }
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
执键写春秋 执键写春秋
3年前
基于Maven工程下的MyBatis基本使用之SQL传单/多参、多表关联查询
MyBatis基本使用声明:基于《基于Maven工程下的MyBatis框架MySQL连接池的数据查询操作》进一步拓展,相关配置文件、数据文件可阅上篇。SQL传单/多参在goods.xml新增两个<select:<!单参数传参,使用paramterType指定的数据类型即可,SQL中value提取参数<selectid"sel
执键写春秋 执键写春秋
3年前
基于Maven工程下的MyBatis框架+MySQL+连接池的数据查询操作
具体操作项目结构引入项目依赖pom.xml<?xmlversion"1.0"encoding"UTF8"?<projectxmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSchemainstance"xsi
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
2星期前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Stella981 Stella981
2年前
Python3:sqlalchemy对mysql数据库操作,非sql语句
Python3:sqlalchemy对mysql数据库操作,非sql语句python3authorlizmdatetime2018020110:00:00coding:utf8'''
Stella981 Stella981
2年前
MyBatis基于Maven的入门
主要内容如下: 1.myBatis在maven中的配置 2.myBatis在工程中的config配置文件3.myBatis为Bean和表的映射文件4.myBatis基本的使用 myBatis在maven中的配置,在pom.xml中增加内容       1.增加依赖 ,mybatis的,还有mysql的驱动的
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究