1、添加
如上图是我们平时在添加数据时展示的页面,而我们在该页面输入想要的数据后添加 提交 按钮,就会将这些数据添加到数
据库中。接下来我们就来实现添加数据的操作。
1.1 编写接口方法
参数:除了id之外的所有的数据。id对应的是表中主键值,而主键我们是 自动增长 生成的。
1.2 编写SQL语句
<insert id="add">
insert into tb_brand (brand_name,company_name,ordered,description,status)
values (#{brandName},#{companyName},#{ordered},#{description},#{status});
</insert>
1.3 编写测试方法并执行
@Test
public void add() throws Exception {
// 0.传参数
int status = 1;
String companyName = "波波手机";
String brandName = "波波";
String description = "手机中的战斗机";
int ordered = 100;
// 封装brand对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setDescription(description);
brand.setBrandName(brandName);
brand.setOrdered(ordered);
//1、加载mybatis的核心配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";//相对路径,基于resources
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.有了工厂对象,就要获取SqlSession对象,执行SQL语句。
SqlSession sqlSession = sqlSessionFactory.openSession();
//SqlSession sqlSession = sqlSessionFactory.openSession(true); //设置自动提交事务,这种情况不需要手动提交事务了
//3.执行sql获取UserMapper接口的代理对象
BrandMapper brandMapper = sqlSe