一、查询操作
代码如下:
<select id="findAll" resultType="com.itlaoqi.mybatis.entity.Goods" > select * from t_goods </select>
二、数据插入
selectKey 可以拿到新增后的id,封装到实体类,通过实体类的属性获取到新增id
<insert id="insert" parameterType="com.itlaoqi.mybatis.entity.Goods"> INSERT INTO `babytun`.`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="int" keyProperty="goodsId" order="AFTER"> <!-- 当前连接中最后产生的id号 --> select last_insert_id() </selectKey> </insert>
Java代码如下:
Goods goods = new Goods(); goods.setTitle("测试商品"); goods.setSubTitle("测试子标题"); goods.setOriginalCost(200f); goods.setCurrentPrice(100f); goods.setDiscount(0.5f); goods.setIsFreeDelivery(1); goods.setCategoryId(43); int result = session.insert("goods.insert", goods); System.out.println(result); System.out.println(goods.getGoodsId());
三、更新操作
进行更新操作时,先对进行需要更新的数据进行查询,得到结果后进行属性的更改,然后在进行更新操作。 xml中sql语句如下:
<!--如果参数是一个基本数据类型或者包装对象(指的就是基本类型的包装类),则使用#{value}代入即可--> <!-- useCache="false"代表不使用缓存 --> <select id="findById" parameterType="Integer" resultType="com.itlaoqi.mybatis.entity.Goods" > select * from t_goods where goods_id = #{value} </select> <update id="update" parameterType="com.itlaoqi.mybatis.entity.Goods" > UPDATE `babytun`.`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>
四、删除操作
删除操作只需根据对应的id进行操作
<delete id="delete" parameterType="Integer"> delete from t_goods where goods_id = #{value} </delete>