使用 Spring JPA 处理软删除 [英] Handling soft-deletes with Spring JPA

查看:77
本文介绍了使用 Spring JPA 处理软删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表 Stuff 定义为...

I have a table Stuff defined as...

id, <fields>..., active

Active 是软删除标志,始终为 10.从长远来看,这可能会被历史表格取代.

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 -

假设你有一个实体狗:

 @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 处理软删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆