Mybatis 新增、修改
使用selectKey
<!--数据插入操作--> <insert id="insertGoods" parameterType="com.imooc.mybatis.entity.GoodsEntity"> <!-- t_goods数据库字段属性,values里javaBean字段属性一一映射 --> 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>
public void testInsert() throws Exception { SqlSession sqlSession = null; try { //获取sql对象 sqlSession = MybatisUtils.openSession(); //实例化goods,插入数据 GoodsEntity goodsEntity = new GoodsEntity(); goodsEntity.setTitle("测试商品"); goodsEntity.setSubTitle("测试商品子标题"); goodsEntity.setOriginalCost(1000f); goodsEntity.setCurrentPrice(800f); goodsEntity.setDiscount(0.8f); goodsEntity.setIsFreeDelivery(1); goodsEntity.setCategoryId(43); //执行sql int num = sqlSession.insert("goods.insertGoods",goodsEntity); //提交数据 sqlSession.commit(); System.out.println(goodsEntity.getGoodsId()); //查看连接状态 Connection conn = MybatisUtils.getConnection(sqlSession); }catch (Exception e){ sqlSession.rollback();//数据回滚 throw e; }finally { MybatisUtils.release(sqlSession); } }
使用 useGeneratedKeys
<!--数据插入操作--> <insert id="insertCategory" parameterType="com.imooc.mybatis.entity.CategoryEntity" useGeneratedKeys="true" keyProperty="categoryId" keyColumn="category_id"> insert into t_category(category_name,parent_id,category_level,category_order) values (#{categoryName},#{parentId},#{categoryLevel},#{categoryOrder}) </insert>
useGeneratedKeys 只能使用于主键自增加的关系性数据库
selectKey 适用于所有关系型数据库
修改操作
<!--数据修改操作--> <update id="updateGoods" parameterType="com.imooc.mybatis.entity.GoodsEntity"> update t_goods set title = #{title} where goods_id = #{goodsId} </update>
public void testUpdate() throws Exception { SqlSession sqlSession = null; try { //获取sql对象 sqlSession = MybatisUtils.openSession(); //实例化goods,插入数据 GoodsEntity goodsEntity = new GoodsEntity(); goodsEntity.setTitle("修改测试"); goodsEntity.setGoodsId(2674); //执行sql int num = sqlSession.update("goods.updateGoods",goodsEntity); //提交数据 sqlSession.commit(); System.out.println(goodsEntity.getTitle()); //查看连接状态 Connection conn = MybatisUtils.getConnection(sqlSession); }catch (Exception e){ sqlSession.rollback();//数据回滚 throw e; }finally { MybatisUtils.release(sqlSession); } }