我使用springMVC集成mybatis,執行SQLMapper配置文件里的insert操作,發現程序沒有報錯,但數據庫表里卻沒有剛才插入的記錄。查了很多資料,終於在一篇博客上找到了答案:在執行完方法后,必須有 session.commit();這句話進行事務提交。因為在做Insert Update Delete的時候,會先開啟事務,而Mybatis不會自動提交(或許可以設置,我還不知道),所以,必須手動提交事務。於是我才調用包含insert操作的方法之后添加session.commit(),記錄成功入庫。
接口定義部分: public interface MenuMapper { public List<MenuVO> getParentMenu(Map<String,Object> paramMap ); public List<MenuVO> getSubMenu(Map<String,Object> paramMap); public int saveMenu(MenuVO menuVo); } 接口調用部分: try{ MenuMapper menuMapper=sqlSession.getMapper(MenuMapper.class); System.out.println(new Gson().toJson(menuvo)); int flag=menuMapper.saveMenu(menuvo); sqlSession.commit(); return flag; }catch (Exception e) { logger.info("存儲菜單失敗,error:"+ e.getMessage()); } finally { sqlSession.close(); } SQL Mapper配置文件:
<!--執行增加操作的SQL語句。id和parameterType分別與MenuMapper接口中的saveMenu方法的名字和參數類型一致。useGeneratedKeys設置為"true"表明要MyBatis獲取由數據庫自動生成的主鍵;keyProperty="menuId"指定把獲取到的主鍵值注入到MenuVO的,menuId屬性--> <insert id="saveMenu" parameterType="MenuVO" useGeneratedKeys="true" keyProperty="menuId"> insert into menu(parentMenuId,menuUrl,menuName) values(#{parentMenuId},#{menuUrl},#{menuName})
</insert>
