我正在尝试在整个平台上实现软删除。每个表都有一个 deleted_on
列,用于过滤掉已删除的行。
这包括我的文件和用户之间的联接表。我没有运气找到任何可以帮助的东西。现在我的类(class)看起来像这样
@Entity
public class File {
@ManyToMany
@JoinTable(
name = "file_user",
joinColumns = @JoinColumn(name = "file_id", referencedColumnName = "file_id"),
inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")
)
private List<User> users;
// Constructor and other fields
}
用户类别:
@Entity
public class User {
@ManyToMany(mappedBy = "users")
private List<FileData> files = new ArrayList<>();
// Constructor and other fields
}
如果可能的话,我希望能够运行以下代码而不在业务代码中过滤它
File file = fileRepository.findOne(fileKey);
file.getUsers().remove(user);
fileRepository.save(file);
最佳答案
如果您使用 Hibernate
作为 JPA 提供者,那么您可以使用 @Where
注释
@Entity
@Where(clause="deleted_on=1")
public class User {
@ManyToMany(mappedBy = "users")
private List<FileData> files = new ArrayList<>();
// Constructor and other fields
}
这会将 where 子句应用到所有具有用户类的查询
附加说明:
您需要在所有关系中再次指定 @where 子句
@ManyToMany
@JoinTable(
name = "file_user",
joinColumns = @JoinColumn(name = "file_id", referencedColumnName = "file_id"),
inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")
)
@Where(clause="deleted_on=1")
private List<User> users;
关于java - 过滤连接表中的行 - Hibernate 中的多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38001174/