jpa批量删除 deleteInBatch方式
jpa批量删除可以调用JpaRepository的deleteInBatch(Iterable<T> entities)
方法,同时把实体列表传参给这个方法。
Service
StudentServiceImpl.java
@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
@Transactional
public List<Student> saveAllStudent(List<Student> studentList) {
List<Student> response = (List<Student>) studentRepository.saveAll(studentList);
return response;
}
@Transactional
public void deleteInBatch(List<Student> studentList) {
studentRepository.deleteInBatch(studentList);
}
}
Repository
在service层调用studentRepository的deleteInBatch方法,StudentRepository之所以有这个方法,是因为它继承了JpaRepository
StudentRepository.java – interface
@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {
}
Controller
最后去controller调用service的方法
StudentController.java
@RestController
@RequestMapping(value = "/student")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "/deleteinbatch", method = RequestMethod.DELETE)
@ResponseBody
public String deleteInBatch(@RequestBody List<Student> studentList) {
studentService.deleteInBatch(studentList);
return "All Students deleted successfully";
}
}