Mybatis-批量操作

批量插入

1
2
3
4
5
6
7
8
9
10
11
12
13
@Insert("<script>" +
"INSERT INTO patent_post_info(patent_id,post_time,post_information) values "+
"<foreach collection =\"postInfos\" item=\"postInfo\" index= \"index\" separator =\",\">" +
"("+
"#{patentId}, " +
"CAST (#{postInfo.postTime} AS timestamp),"+
"#{postInfo.postInformation}"+
")" +
"</foreach >"+
"</script>"
)
Integer insertPatentPostInfo(@Param("patentId")Integer id, @Param("postInfos")List<PatentPostInfo> postInfos)
throws SQLException;

批量更新

以下示例展示了更新两个字段,每一个字段使用一个片段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Update("<script>"+
"UPDATE order_items " +
"SET " +
"goods_total_price=" +
"<foreach collection=\"orderItems\" item=\"orderItem\"index=\"index\" separator=\" \" open=\"CASE id\" close=\"END\">" +
"WHEN #{orderItem.id} THEN #{orderItem.goodsTotalPrice}" +
"</foreach>" +
",goods_name="+
"<foreach collection=\"list\" item=\"orderItem\" index=\"index\" separator=\" \" open=\"CASE id\" close=\"END\">" +
"WHEN #{orderItem.id} THEN #{orderItem.goodsName}" +
"</foreach>" +
"WHERE id IN " +
"<foreach collection=\"list\" item=\"orderItem\" index=\"index\" separator=\",\" open=\"(\" close=\")\">" +
"#{orderItem.id}"+
"</foreach>" +
"</script>")
Integer bathUpdateOrderItem(@Param("orderItems")List<OrderItemCustom> orderItems) throws SQLException;

批量删除

使用数组接受参数

1
2
3
4
5
6
7
8
@Delete("<script>" +
"DELETE FROM order_items WHERE id IN" +
"<foreach collection=\"ids\" item=\"itemId\" index=\"index\" separator=\",\" open=\"(\" close=\")\">"+
"#{itemId}" +
"</foreach>"+
"</script>"
)
Integer bathdeleteOrderItem(@Param("ids") Integer[] itemIds)throws SQLException;

controller中使用 @RequestParam 注解修饰数组,请求时将参数拼接到url后面(类似Get请求)