1 實現添加操作
- 編寫接口方法:Mapper接口
- 編寫sql語句:sql映射文件
<insert id="add">insert into tb_brand(brand_name,company_name,ordered,description,status)values(#{brandName},#{companyName},#{ordered},#{description},#{status});</insert>
- 執行方法,測試
MyBatis事務:
- openSession():默認開啟事務,進行增刪改操作后需要使用sqlSession.commit();手動提交事務
- openSession(true):設置為自動提交事務(關閉事務)
@Testpublic void testAdd() throws Exception{int status = 1;String brandName = "波導";String companyName = "波導手機";String description = "手機中的戰斗機";int ordered = 100;Brand brand = new Brand();brand.setStatus(status);brand.setBrandName(brandName);brand.setCompanyName(brandName);brand.setDescription(description);brand.setOrdered(ordered);// 加載mybatis的核心配置文件,獲取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 獲取SqlSession對象,用它來執行sqlSqlSession sqlSession = sqlSessionFactory.openSession();// 獲取UserMapper接口的代理對象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);brandMapper.add(brand);sqlSession.commit();sqlSession.close();}
2 主鍵返回
在數據添加成功后,需要獲取插入數據庫數據的主鍵的值
比如:添加訂單和訂單項
- 添加訂單
- 添加訂單項,訂單項中需要設置所屬訂單的id
解決:
<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>