使用mybatis执行对应的SQL Mapper配置中的insert、update、delete等标签操作,数据库记录不变

我使用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>

 

 

posted @ 2015-06-01 17:27  luoluo,keep moving...  阅读(8129)  评论(0编辑  收藏  举报