Вы пытаетесь реализовать «мягкое удаление», чтобы попробовать этот подход:
Пользовательский объект :
@Entity
User {
@Id
@GeneratedValue
private Integer id;
//...
private boolean removed; // user is removed if this property is true
//...
}
Пользовательский сервис :
public interface UserService {
Optional<Integer> softDelete(int id);
}
@Service
public UserServiceImpl implements UserService (
// Injecting UserRepo
// First variant - read the user, set it removed, then updated it.
@Transactional
Optional<Integer> softDelete1(int id) {
// Using method findById from Spring Boot 2+, for SB1.5+ - use method findOne
return userRepo.findById(id).map(user -> {
user.setRemoved(true);
userRepo.save(user);
return 1;
});
}
// Second variant - update the user directly
@Transactional
Optional<Integer> softDelete2(int id) {
return userRepo.softDelete(id);
}
}
Пользовательский контроллер :
@RestController
@RequestMapping("/users")
public class UserController {
// Injecting UserService
@DeleteMapping("/{id}")
public ResponseEntity<?> softDelete(@PathVariable("id") int id) {
return userService.softDelete1(id) // you can use 1 or 2 variants
.map(i -> ResponseEntity.noContent().build()) // on success
.orElse(ResponseEntity.notFound().build()); // if user not found
}
}
Пользовательское репо :
public interface UserRepo extends JpaRepository<User, Integer>() {
@Modifying(clearAutomatically = true)
@Query("update User u set u.removed = true where u.id = ?1")
int remove(int id);
default Optional<Integer> softDelete(int id) {
return (remove(id) > 0) ? Optional.of(1) : Optional.empty();
}
}
ОБНОВЛЕНО
Или, я думаю, вы можете просто попытаться просто переопределить deleteById
метод CrudRepository
(не тестировался - пожалуйста, оставьте отзыв):
@Override
@Modifying(clearAutomatically = true)
@Query("update User u set u.removed = true where u.id = ?1")
void deleteById(Integer id);
затемиспользуйте это в своем сервисе.