Mybatis实现添加操作
1 普通的添加
返回值为void 通过是否有异常报错来看添加是否成功
接口
/**
* 添加
*/
void add(Brand brand);
sql映射
<!--添加-->
<insert id="add">
insert into tb_brand (brand_name, company_name, ordered, description, status)
values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
</insert>
测试
@Test
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);
// 5. 提交事务
sqlSession.commit();
// 6. 释放资源
sqlSession.close();
}
这里的测试案例使用了一行新的代码
sqlSession.commit();
这是提交事务。因为当SQL执行完之后,只是在MyBatis执行完了,它不会自动提交事务,所以在数据库还是看不到。所以加上这一行让他自动提交事务。或者
SqlSession sqlSession = sqlSessionFactory.openSession(true)
这样也可以自动提交事务
2 主键返回
在一些场景中,我们添加完数据后,需要返回这条数据的主键值
只需要在sql配置的时候添加两个属性
<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>
useGeneratedKeys设置为 true, keyProperty里面放的是主键的名称
测试
@Test
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);
Integer id = brand.getId();
System.out.println(id);
// 5. 提交事务
sqlSession.commit();
// 6. 释放资源
sqlSession.close();
}