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.执行方法,测试