增加
1.增刪改在接口中的返回值
Integer、Long、Boolean、void 返回影響多少行 或 true | false
2.mapper 中 增刪改沒有返回值 (resultType或resultMap)
3.mysql支持自增主鍵,自增主鍵的值的獲取,mybatis利用statement.getGeneratedKey();
userGeneratedKeys="true" :使用自增主鍵獲取主鍵的策略
keyProperty:指定對應的主鍵屬性,也就是mybatis獲取到主鍵值以后,將這個值封裝到JavaBean中哪個屬性中
獲取則是通過插入后,在查詢一遍插入的對象,就可以拿到主鍵值
4.sqlSessionFactory.openSession()需要手動提交事務,或者采用sqlSessionFactory.openSession(true)
public interface EmployeeMapper { Integer addEmp(Employee employee); }
<!-- mysql支持自增主鍵,自增主鍵的值的獲取,mybatis利用statement.getGeneratedKey(); userGeneratedKeys="true" :使用自增主鍵獲取主鍵的策略 keyProperty:指定對應的主鍵屬性,也就是mybatis獲取到主鍵值以后,將這個值封裝到JavaBean中哪個屬性中 --> <insert id="addEmp" useGeneratedKeys="true" keyProperty="id"> INSERT INTO tbl_employee(last_name, email, gender) VALUES (#{name}, #{email}, #{gender}) </insert>
@Test public void addEmp() throws IOException { //讀取配置文件 InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); //創建sqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //獲取sqlSession實例,能直接執行已經映射的sql語句
//不會自動提交,除非在openSession(true) SqlSession sqlSession = sqlSessionFactory.openSession(); //執行查詢方法 try { EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); Employee employee = new Employee(null,"麥克雷",'1',"mapleins@qq.com"); //i判斷是否插入成功 Integer i = mapper.addEmp(employee); System.out.println(i); //可以獲取插入后的主鍵值 System.out.println(employee.getId()); sqlSession.commit(); }finally { //關閉sqlSession sqlSession.close(); } }
刪除和修改
public interface EmployeeMapper { Long updateEmp(Employee employee); Boolean deleteEmpById(Integer id); }
<update id="updateEmp"> UPDATE tbl_employee SET last_name=#{name}, email=#{email}, gender=#{gender} WHERE id = #{id} </update> <delete id="deleteEmpById"> delete from tbl_employee where id = #{id} </delete>
@Test public void updateEmp() throws IOException { //讀取配置文件 InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); //創建sqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //獲取sqlSession實例,能直接執行已經映射的sql語句 SqlSession sqlSession = sqlSessionFactory.openSession(); //執行查詢方法 try { EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); Employee employee = new Employee(17,"天使",'0',"mapleins@qq.com"); Long l = mapper.updateEmp(employee); System.out.println(l); sqlSession.commit(); }finally { //關閉sqlSession sqlSession.close(); } } @Test public void deleteEmpById() throws IOException { //讀取配置文件 InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); //創建sqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //獲取sqlSession實例,能直接執行已經映射的sql語句 SqlSession sqlSession = sqlSessionFactory.openSession(); //執行查詢方法 try { EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); Boolean b = mapper.deleteEmpById(17); System.out.println(b); sqlSession.commit(); }finally { //關閉sqlSession sqlSession.close(); } }