SpringBoot2 Jpa 批量删除

前台处理

首先前台先要获取所有的要删除数据的ID,并将ID拼接成字符串 例如: 2,3,4,5,然后通过GET请求返送到后台。

后台处理

控制器接收
/**
 * @function 批量删除
 * @param stu_id
 * @return
*/
@GetMapping("/del_stu")
@ResponseBody
public Msg batch_del_stu(@RequestParam("stu_id") String stu_id){
    // 接收包含stuId的字符串,并将它分割成字符串数组
    String[] stuList = stu_id.split(",");
    // 将字符串数组转为List<Intger> 类型
    List<Integer> LString = new ArrayList<Integer>();
    for(String str : stuList){
        LString.add(new Integer(str));
    }
    // 调用service层的批量删除函数
    studentsService.deleteBatch(LString);
    return Msg.success().add("数组", LString);
}
service层
    @Override
    public void deleteBatch(List<Integer> stuList) {
        // 第一种批量删除方法,是通过spring data中继承JpaRepository接口后,通过关键字拼接的方法进行删除,删除时候是通过ID一条一条删除的
//      studentsRepository.deleteStudentsByStuIdIn(stuList);
        // 第二种批量删除方法, 是通过自定义JPQL语句进行删除,使用的是 where stuId in ()的操作
        studentsRepository.deleteBatch(stuList);
    }
Repository接口层
public interface StudentsRepository extends Repository<Students, Integer>, JpaRepository<Students, Integer> {

    /**
     * @function 自定义JPQL
     * @param ids
     */
    // 注意更新和删除是需要加事务的, 并且要加上 @Modify的注解
    @Modifying
    @Transactional
    @Query("delete from Students s where s.stuId in (?1)")
    void deleteBatch(List<Integer> ids);

    // 这个是通过spring data拼接关键字进行的操作
    void deleteStudentsByStuIdIn(List<Integer> ids);

}

附加

@Modifying注解

1、在@Query注解中编写JPQL实现DELETE和UPDATE操作时候必须加上@Modifying注解,通知Spring Data这是一个delete或者updata操作

2、 updata和delete操作需要使用事务,此时需要定义service层,在service方法上添加事务操作

3、 注意JPQL不支持insert操作

@Query 如果在注解中添加 nativeQuery=true 是支持原生SQL查询

猜你喜欢

转载自blog.csdn.net/yhflyl/article/details/81557670
今日推荐