您的位置:首页 > 产品设计 > UI/UE

allowMultiQueries 执行多条SQL语句

2017-11-30 20:58 471 查看

allowMultiQueries

在使用Mybatis时,写数据操作的方法时,一般为执行一条SQL语句,如下面代码所示为,Category数据表对应的数据增删改查方法。

<insert id="addCategory" parameterType="Category">
insert into category_ ( name ) values (#{name})
</insert>

<delete id="deleteCategory" >
delete from category_ where id=#{id};
</delete>

<select id="getCategory" parameterType="_int" resultType="Category">
select * from category_ where id=#{id}
</select>

<update id="updateCategory" parameterType="Category">
update category_ set name=#{name} where id=#{id}
</update>

<select id="listCategory" resultType="Category">
select * from category_
</select>
但在一对多,多对一的情况下,存在一些问题。如:一个Category对应多个Product,当你删除Category时,同时也需要删除其包含的Product。如图下图所示,Product表中的cid外键映射Category表中的id。当我们删除category 1这一行数据时,希望同时也删除其对应的product a和product b。



因此,执行一个删除方法时,要对Category和Product两个表删除数据,执行两条SQL语句。如下代码所示,这两条删除语句的顺序也是很有讲究的,如果你添加了外键关系,那么先要删除外键中的数据,后删除主键中的数据。因为,主键被其他外键所引用时是无法删除的。这里,我们先执行product表中的删除,后执行category表中的删除:

<delete id="deleteCategory" >
delete from product_ where cid=#{id};
delete from category_ where id=#{id};
</delete>
当同时执行多条SQL语句的时候,需要在Mybatis配置文件中进行allowMultiQueries配置:    
<property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8&allowMultiQueries=true"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: