標籤:
我使用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>
使用mybatis執行對應的SQL Mapper配置中的insert、update、delete等標籤操作,資料庫記錄不變