我尝试在父实体和子实体之间实现软删除,当它实现双向时,它可以像双向一样工作,但当它实现单向时,它设置了一个空id引用。
User.java
@Getter
@Setter
@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "user")
@SQLDelete(sql = "UPDATE user SET is_deleted = true WHERE id = ? and version = ? " )
@Where(clause = "is_deleted = false")
public class User extends AbstractBaseModel {
private String firstName;
private String lastName;
private String email;
.
.
.
@OneToMany(mappedBy = "task", cascade = CascadeType.ALL)
private List<Tasks> tasks;
}
字符串
Task.java
在用户和任务之间存在双向引用
@Getter
@Setter
@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "task")
@SQLDelete(sql = "UPDATE task SET is_deleted = true WHERE id = ? and version = ? " )
@Where(clause = "is_deleted = false")
public class Task extends AbstractBaseModel {
private String taskName;
private String lastState;
.
.
.
@ManyToOne(fetch = FetchType.LAZY)
private User user;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "task_id", referencedColumnName = "id")
private List<TaskHistory> taskHistory;
}
型
TaskHistory.java
这里没有引用在任务和任务历史记录之间有单向引用
@Getter
@Setter
@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "task_history")
@SQLDelete(sql = "UPDATE task_history SET is_deleted = true WHERE id = ? and version = ? " )
@Where(clause = "is_deleted = false")
public class TaskHistory extends AbstractBaseModel {
private String state;
.
.
.
}
型
当使用JPA删除用户时,如下所示
userRepository.deleteById(id);
型
它运行了四个查询
Hibernate: update task_history set task_id=null where task_id=? and ((is_deleted = false) )
Hibernate: UPDATE task_history SET is_deleted = true WHERE id = ? and version = ?
Hibernate: UPDATE task SET is_deleted = true WHERE id = ? and version = ?
Hibernate: UPDATE user SET is_deleted = true WHERE id = ? and version = ?
型
不希望第一个查询。当设置task_id=null时,无法返回第一种情况
1条答案
按热度按时间sgtfey8w1#
我用下面的代码解决了我的问题@JoinColumn(name =“task_id”,referencedColumnName =“id”,nullable = false)当删除用户休眠不能设置null时