问题描述
我有一张桌子 Stuff
定义为......
I have a table Stuff
defined as...
id, <fields>..., active
有效是软删除标志,始终是 1
或 0
。从长远来看,这可能会偏向于历史表。
Active is the soft-delete flag and is always 1
or 0
. Long term this may go away in favor of a historical table.
public interface StuffRepository extends JpaRepository<StuffEntity, Long> {}
在代码中,我们总是使用活动记录。有没有办法让Spring始终为为此存储库生成的查询附加 active = 1
条件?或者更理想的是允许我扩展用于生成查询的语法?
In code, we always use active records. Is there any way to get Spring to always append an active=1
condition to queries generated for this repository? Or more ideally allow me to extend the grammar used to generate the queries?
我知道我可以创建命名 @queues
无处不在,但后来我失去了生成查询的便利性。我还想避免使用活动方法来污染接口。
I understand that I can create named @queues
everywhere but then I lose the convenience of the generated queries. I also want to avoid polluting the interface with "active" methods.
如果重要的话,我使用Hibernate 4.2作为我的JPA实现。
I am using Hibernate 4.2 as my JPA implementation if that matters.
推荐答案
这是一个老问题,你可能已经找到了答案。但是,所有Spring / JPA / Hibernate程序员都在那里寻求答案 -
This is an old question, and you probably already found the answer. BUT, for all the Spring/JPA/Hibernate programmers out there seeking for answer -
假设你有一个实体Dog:
Say you have an entity Dog:
@Entity
public class Dog{
......(fields)....
@Column(name="is_active")
private Boolean active;
}
和存储库:
public interface DogRepository extends JpaRepository<Dog, Integer> {
}
您需要做的就是在实体级别添加@Where注释,结果:
All you need to do is add the @Where annotation on the entity level, resulting:
@Entity
@Where(clause="is_active=1")
public class Dog{
......(fields)....
@Column(name="is_active")
private Boolean active;
}
存储库执行的所有查询都会自动过滤掉非活动状态 行。
All the queries performed by the repository will automatically filter out the "non-active" rows.
这篇关于使用Spring JPA处理软删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!