您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
11-添加&修改功能(insert、update标签、useGeneratedKeys、keyProperty属性、commit方法、openSession参数)
发布时间:2024-11-21 20:10:08编辑:雪饮阅读()
-
添加
要实现添加数据到mysql数据库的数据表中,需要在mapper映射文件中定义insert标签
<insert id="add">
insert into tb_brand (brand_name,company_name,ordered,description,status)
values (#{brandName},#{companyName},#{ordered},#{description},#{status})
</insert>
然后mapper接口中定义抽象方法
void add(Brand brand);
然后正式添加数据后还要提交事务,因为默认情况下事务关闭自动提交的。
则测试方法如:
@Test
public void test6() throws IOException {
String resource="mybatis-config.xml";
InputStream inputStream= Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
String brandName="松鼠";
Brand brand=new Brand();
brand.setBrandName(brandName);
brandMapper.add(brand);
sqlSession.commit();
sqlSession.close();
}
开启自动提交
当然你也可以开启自动提交,则数据添加后就不用再次提交了
SqlSession sqlSession=sqlSessionFactory.openSession(true);
获取主键id
如果想要获取新增后的主键id值,则需要在insert标签配置useGeneratedKeys为true,并且使用keyProperty指定主键属性名。
则这里insert标签修改后如
<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>
那么获取主键id就是直接在新增后会赋值于当前POJO的实例对象的属性上面,如
brandMapper.add(brand);
System.out.println(brand.getId());
修改
要实现对mysql数据的数据表进行update操作,需要在mapper文件中定义update标签,那么当要动态的去更新某个字段,或某几个字段的时候难免会有set后面每个字段后面的逗号问题,同样的和前番处理查询时候的where中的一样,这里也有解决方案就是用set标签嵌套,然后你尽管每个set的字段值后面加逗号即可,会自动帮你处理的。
所以update标签实现如:
<update id="update">
update tb_brand
<set>
<if test="status != null">
status=#{status},
</if>
<if test="companyName != null and companyName != '' ">
company_name = #{companyName},
</if>
<if test="brandName != null and brandName != '' ">
brand_name = #{brandName},
</if>
</set>
where id=#{id}
</update>
mapper接口中的抽象方法就很简单了
int update(Brand brand);
然后测试添加如:
@Test
public void test7() throws IOException {
String resource="mybatis-config.xml";
InputStream inputStream= Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession(true);
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
String brandName="松鼠";
Brand brand=new Brand();
brand.setId(1);
brand.setBrandName(brandName);
brandMapper.update(brand);
sqlSession.close();
}
关键字词:insert,update,useGeneratedKeys,keyProperty,commit,openSession
上一篇:10-查询-动态条件查询(if、where、choose、when、otherwise标签)
下一篇:12-删除功能(delete、foreach标签,collection,item,separator,open,close属性)