jdbc.properties中的allowMultiQueries=true代表可以在一个insert标签中执行多个sql语句,具体实例如下:
测试文件中:
@Test
public void 批量添加资源03() throws Exception {
List<Menu> menuList = new ArrayList<Menu>();
Menu menu = new Menu();
menu.setMenu_id(1);
menuList.add(menu);
menu = new Menu();
menu.setMenu_id(2);
menuList.add(menu);
menu = new Menu();
menu.setMenu_id(3);
menuList.add(menu);
Role role = new Role();
role.setRole_id(8);
this.roleDao.addMenuByRole(role, menuList);
this.sqlSession.commit();
}
映射文件中如下所示:
<!-- 事务:两个sql语句 -->
<insert id="addMenuByRole">
DELETE FROM role_link_menu WHERE fk_role_id = #{role.role_id};
INSERT INTO
role_link_menu
(fk_role_id,fk_menu_id)
VALUES
<foreach collection="menus" item="menu" separator=",">
(#{role.role_id},#{menu.menu_id})
</foreach>
</insert>