尽管该方法deleteById
Spring Data Jpa
确实有效,但它不会从数据库中删除该对象。我读到这是因为该对象具有关系ManyToOne
并且对其的引用保留在父实体中,该实体存储这些对象的列表,首先您需要从该列表中删除该对象。但是如何才能做到这一点,才能不加载整个对象列表(其中可能有数千个)?
我翻遍了PgAdmin
(图形数据库管理界面PostgreSQL
):在那里我没有找到entity1_entity2
主表之间的任何关系表(如)。
CascadeType
由于某种原因,它对我也不起作用。
确切地说,不可能删除与实体和Comment
相关的对象。ManyToOne
Person
Task
这是两个父实体Person
和Task
:
@Entity
@Table(name = "people")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
private String name;
@Email
private String email;
@Size(min = 5, message = "Пароль должен содержать минимум 5 символов")
private String password;
private transient String passwordConfirm;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "author")
private List<Task> createdTasks;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "executor")
private List<Task> executableTasks;
@CreatedDate
private LocalDateTime registrationDate;
public Person(){}
// getters, setters
@Entity
@Table(name = "tasks")
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Заголовок не может быть пустым")
private String title;
@NotBlank(message = "Описание не может быть пустым")
private String description;
@NotNull(message = "У задачи должен быть статус")
@Enumerated(EnumType.STRING)
private Status status;
@NotNull(message = "У задачи должен быть приоритет")
@Enumerated(EnumType.STRING)
private Priority priority;
@ManyToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "author_id", referencedColumnName = "id")
private Person author;
@ManyToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "executor_id", referencedColumnName = "id")
private Person executor;
@NotNull(message = "У задачи должен быть исполнитель")
private transient long executorId;
@OneToMany(mappedBy = "task")
private List<Comment> comments;
@CreatedDate
private LocalDateTime createdAt;
private LocalDateTime editedAt;
public Task(){}
// getters, setters
子实体Comment
:
@Entity
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Комментарий не может быть пустым")
private String body;
@ManyToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "task_id", referencedColumnName = "id")
private Task task;
private transient long taskId;
@ManyToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "author_id", referencedColumnName = "id")
private Person author;
@CreatedDate
private LocalDateTime createdAt;
private LocalDateTime editedAt;
public Comment(){}
// getters, setters
控制器方法:
@DeleteMapping("/comment/delete/confirm/{id}")
public String deleteComment(@PathVariable long id, Model model, @AuthenticationPrincipal PersonDetails pd) {
Comment comment = commentService.findById(id);
if (pd == null || comment.getAuthor().getId() != pd.getPerson().getId())
throw new MismatchIdentifierException("ID автора комментария и Ваш не совпадают. Похоже, что Вы не являетесь автором.");
commentService.deleteById(id);
System.out.println("\n\n\n\ndeleting succesful");
model.addAttribute("task", comment.getTask());
return showTask(comment.getTask().getId(), model, pd);
}
结果,显示一条消息"deleting succesful"
。
服务方式:
public void deleteById(long id) {
commentRepository.deleteById(id);
}
存储库:
@Repository
public interface CommentRepository extends JpaRepository<Comment, Long> {
@Query(value = "SELECT * from comments WHERE task_id = ?1", nativeQuery = true)
List<Comment> findByTask(long id);
@Query(value = "SELECT * from comments WHERE author_id = ?1", nativeQuery = true)
List<Comment> findByAuthor(long id);
Page<Comment> findByAuthor_id(long id, Pageable pageable);
}