// mapper
void add(Brand brand);
//BrandMapper.xml
<insert id="add" >
insert into tb_brand(brand_name, company_name, ordered, description, status)
values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status})
;
</insert>
//Test
// 封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered);
mapper.add(brand);
// 提交事务
sqlSession.commit();
因为这里数据库中的事务未设置自动提交所以会自动回滚,需要i自己手动提交事务。
// 设置自动提交事务或者手动提交事务 false为手动提交事务
SqlSession sqlSession = sessionFactory.openSession(true);
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into tb_brand(brand_name, company_name, ordered, description, status)
values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status})
;
</insert>
System.out.println(brand.getId());
1. 修改全部字段
2. <update id="update">
update tb_brand
set brand_name = #{brandName},
company_name = #{companyName},
ordered = #{ordered},
description = #{description},
status = #{status}
where
id = #{id};
</update>
int update = mapper.update(brand);
System.out.println(update);
</update>
<update id="updatesingle">
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="description != null and description != ''">
description = #{description},
</if>
<if test="ordered != null and ordered != ''">
ordered = #{ordered},
</if>
<if test="status != null and status != ''">
status = #{status}
</if>
where
id = #{id};
</update>
//mapper
void deleteById(int id);
//BrandMapper.xml
<delete id="deleteById">
delete
from tb_brand
where id = #{id};
</delete>
<delete id="deleteMulti">
delete
from tb_brand
where id
in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
;
</delete>
//mapper
void deleteMulti(@Param("ids") int[] ids);
//BrandMapper.xml
<delete id="deleteMulti">
delete
from tb_brand
where id
in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
;
</delete>
删除时需要进行备注默认为collection 里面传入数组默认为array 可以使用注解@param(" ")设置姓名
MyBatis对参数的封装
注: 不要使用默认名称 使用@Param注解即可
@Delete("delete from tb_user where id = #{id}")
void deleteById(int id);
直接调用即可