springboot~jpa优雅的软删除能力
<p>之前写过关于springboot~jpa优雅的处理isDelete的默认值的文章,今天说一下在jpa或者其它类型的Repository中实现软删除的方法,主要借助了自定义的仓储的能力。</p><h1 id="优雅的引用方式">优雅的引用方式</h1>
<pre><code>/**
* 开启软删除的能力
*
* @author lind
* @date 2025/9/8 11:24
* @since 1.0.0
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@EnableJpaRepositories(repositoryBaseClass = SoftDeleteRepositoryImpl.class)
public @interface EnableSoftDeleteRepository {
}
</code></pre>
<h1 id="接口标准化">接口标准化</h1>
<pre><code>/**
* 软删除能力,通过@EnableSoftDeleteRepository注解开启功能,通过接口继承的方式实现这个能力
*
* @param <T>
* @param <ID>
*/
@NoRepositoryBean // 不让jpa使用代理建立实现类
public interface SoftDeleteRepository<T, ID> {
T getEntityById(ID id);
/**
* 希望重写findById方法
* @param id
* @return
*/
T getById(ID id);
}
</code></pre>
<h1 id="覆盖默认的deletebyid方法实现软删除">覆盖默认的deleteById方法,实现软删除</h1>
<pre><code>/**
* 自定义的公共仓储的实现
*
* @param <T>
* @param <ID>
*/
public class SoftDeleteRepositoryImpl<T, ID> extends SimpleJpaRepository<T, ID> implements SoftDeleteRepository<T, ID> {
private final EntityManager entityManager;
private final JpaEntityInformation<T, ID> jpaEntityInformation;
Class<T> domainType;
Logger logger = LoggerFactory.getLogger(SoftDeleteRepositoryImpl.class);
public SoftDeleteRepositoryImpl(JpaEntityInformation<T, ID> jpaEntityInformation, EntityManager entityManager) {
super(jpaEntityInformation, entityManager); // 必须调用父类构造函数
this.entityManager = entityManager;
this.jpaEntityInformation = jpaEntityInformation;
this.domainType = jpaEntityInformation.getJavaType();
}
@Override
public T getEntityById(ID id) {
return entityManager.find(this.domainType, id);
}
/**
* @param id
* @deprecated
*/
@Override
public void deleteById(ID id) {
logger.info("CustomRepositoryImpl.getById " + id);
T entity = getEntityById(id);
if (entity != null && entity instanceof DeletedFlagField) {
((DeletedFlagField) entity).setDeletedFlag(1);
entityManager.merge(entity);
}
else {
super.deleteById(id);
}
}
}
</code></pre>
<p>需要实现软删除的仓库接口上,继承这个接口即有这个软删除的能力</p>
<pre><code>/**
* 用户仓储
*
* @author lind
* @date 2025/7/15 15:56
* @since 1.0.0
*/
public interface UserEntityRepository extends SoftDeleteRepository<UserEntity, String>,
JpaRepository<UserEntity, String>, JpaSpecificationExecutor<UserEntity> {
}
</code></pre>
</div>
<div id="MySignature" role="contentinfo">
<p></p>
<div class="navgood">
<p>作者:仓储大叔,张占岭,<br>
荣誉:微软MVP<br>QQ:853066980</p>
<p><strong>支付宝扫一扫,为大叔打赏!</strong>
<br><img src="https://images.cnblogs.com/cnblogs_com/lori/237884/o_IMG_7144.JPG"></p>
</div><br><br>
来源:https://www.cnblogs.com/lori/p/19663968
頁:
[1]