添加、修改
1.编写接口方法:Mapper接口
2.编写SQL语句:SQL映射文件
3.试行方法,测试
4.获取id
5.修改动态字段
1.编写Mapper接口方法
void add(Brand brand);
2.编写SQL映射文件
<insert id="add">
insert into tb_brand (brand_name, company_name, ordered, description, status)
values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
</insert>
注意添加的时候,命名规则的问题。
3.测试
public void testAdd() throws IOException {
//接收参数
int status = 1;
String companyName = "波导手机";
String brandName = "波导";
String description = "手机中的战斗机";
int ordered = 100;
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered);
//1. 获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2. 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3. 获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4. 执行方法
brandMapper.add(brand);
//提交事务
sqlSession.commit();
//5. 释放资源
sqlSession.close();
}
注意:这里有MyBatis事务问题
1.openSession():默认开启事务,进行增删改查操作后需要使用sqlSession.commit();手动提交事务。
2.openSession(true):可以设置为自动提交事务(关闭事务)。mysql中的@@autocommit默认提交方式。
4.获取id
在添加完数据之后,是不能够直接获取id值得。
需要编写SQL语句中添加:
<insert id="add" useGeneratedKeys="true" keyProperty="id">
在插入的时候,id值就已经存在了,只是需要绑定到对应的对象上面,令keyProperty指向id属性的名称即可。
5.修改动态字段
当只用更改部分字段时,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">
ordered = #{ordered},
</if>
<if test="description != null and description != ''">
description = #{description},
</if>
<if test="status != null">
status = #{status}
</if>
</set>
where id = #{id};
</update>
注意使用set标签:
当其中只有一个SQL字段生效时,后面的逗号就会出现语法错误,为了避免,采用set标签。