后端学习笔记(6)--添加删除

3.添加

1.编写接口方法:Mapper接口

​ *参数:除了id之外的所有数据

​ *结果:void

void add(Brand brand);

2.编写SQL语句:SQL映射文件

<insert id="add">
    insert into tb_brand(brand_name,company_name,ordered,description,status) values(#{brandName},#{companyName },#{ordered},#{description},#{status});
</insert>

3.执行方法,测试

​ *MyBatis事务:

*openSession():默认开启事务,进行增删改操作后需要使用sqlSession.commit();手动提交事务

*openSession(true):可以设置为自动提交事务(关闭实物)

4.主键返回

​ *在数据添加成功后,需要获取插入数据库数据的主键的值

​ *比如:添加订单和订单项

1.添加订单

2.添加订单项,订单项中需要设置所属订单的id

<insert id="addOrder" useGeneratedKeys="true" keyProperty="id">
    insert into tb_order(payment,payment_type,status)
    values(#{payment},#{paymentType},#{status});
</insert>
<insert id="addOrderItem">
    insert into tb_order(goods_name,goods_price,count,order_id)
    values(#{goodsName},#{goodsPrice},#{count},#{orderId});
</insert>

1.修改全部字段

1.编写接口方法:Mapper接口

​ *参数:所有数据

​ *结果:void

void update(Brand brand);

2.编写SQL语句:SQL映射文件

<update id="update">
    update tb_brand
    set brand_name=#{brandName},
		company_name=#{companyName},
		ordered=#{ordered},
		description=#{description},
		status=#{status}
	where id=#{id};
</update>

3.执行方法,测试

2.修改动态字段

1.编写接口方法:Mapper接口

​ *参数:部分数据,封装到对象中

​ *结果:void

<update id="update">
    update tb_user
    set username=#{username},
		password=#{password},
		gender=#{gender},
		addr=#{addr},
	where id=#{id};
</update>

2.编写SQL语句:SQL映射文件

<update id="update">
    update tb_brand
	<set>
    	<if test="brandName != null and brandName !="">
            brand_name = #{brandName},
		</if>
    	<if test="companyName != null and companyName !="">
            company_name = #{companyName},
		</if>
    	<if test="ordered != null and ordered !="">
            ordered = #{ordered},
		</if>
    	<if test="description != null and description !="">
            brand_name = #{brandName},
		</if>
    	<if test="status != null>
            status = #{status},
		</if>
    </set>
	where id=#{id};
</update>

3.执行方法:测试

4.删除

1.删除一个

1.编写接口方法:Mapper接口

​ *参数:id

​ *结果:void

void deleteById(int id);

2.编写SQL依据:SQL映射文件

<delete id="deleteById">
    delete from tb_brand where id =#{id}
</delete>

3.执行方法,测试

2.批量删除

1.编写接口方法:Mapper接口

​ *参数:id数组

​ *结果:void

void deleteByIds(@Param("ids") int[] ids);

2.编写SQL语句:SQL映射文件

<delete id="deleteByIds">
    delete from tb_brand
    where id in(?,?,?)	//占位符
</delete>
<delete id="deleteByIds">
    delete from tb_brand
    where id in
    <foreach collection="ids" item="id" seperator="," open="("close=")"> #{id}
	</foreach>	//foreach可以完成数组或元素的遍历
</delete>

3.执行方法,测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值