1.insert:在标签内写inser的sql语句
配置文件:
<insert id="addEmp" parameterType="cn.it.mybatis.bean.Employee"> INSERT INTO tbl_employee(last_name,gender,email) VALUE(#{lastName},#{gender},#{email}) </insert>
测试代码:
@Test void test02() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); // 不自动提交数据 // sqlSessionFactory.openSession(true)自动提交数据 SqlSession openSession = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); // 添加一个新员工 mapper.addEmp(new Employee(null, "张三", "123@qq.com", "1")); // 手动提交数据 openSession.commit(); } finally { openSession.close(); } }
执行结果:
2.update:标签内写update的sql语句
配置文件:
<update id="updateEmp"> UPDATE tbl_employee SET last_name=#{lastName},gender=#{gender},email=#{email} WHERE id=#{id} </update>
测试代码:
@Test void test03() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); // 修改1号员工信息 mapper.updateEmp(new Employee(1, "李四", "789@qq.com", "1")); openSession.commit(); } finally { openSession.close(); } }
执行结果:
修改了id为1号的信息
3.delete:在标签中写delete的sql语句
配置文件:
<delete id="deleteEmp"> DELETE FROM tbl_employee WHERE id=#{id} </delete>
测试代码:
@Test void test04() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); // 删除1号员工信息 mapper.deleteEmp(1); openSession.commit(); } finally { openSession.close(); } }
执行结果:
已经删除1号员工
MyBatis允许增删改直接定义以下类型的返回值,
Integer、Long、Boolean
获取自增主键的值(仅对 insert 和 update 有用):
MySql支持自增主键,自增主键的值获取。而MyBatis也是使用statement.getGenreatedKeys(),来获取自增主键的值。
useGeneratedKeys="true":开启自增主键获取主键值的功能
keyProperty:指定对应的主键属性,也就是MyBatis获取到的主键值后,将这个值封装给javaBean的哪个属性。
如果是非自增的数据库:
可以使用selectKey使查询主键的sql提前运行,封装在javaBean的属性中,然后再在使用主键值