springboot~jpa优雅的软删除能力

之前写过关于springboot~jpa优雅的处理isDelete的默认值的文章,今天说一下在jpa或者其它类型的Repository中实现软删除的方法,主要借助了自定义的仓储的能力。

优雅的引用方式

/**
 * 开启软删除的能力
 *
 * @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 {

}

接口标准化

/**
 * 软删除能力,通过@EnableSoftDeleteRepository注解开启功能,通过接口继承的方式实现这个能力
 *
 * @param <T>
 * @param <ID>
 */
@NoRepositoryBean // 不让jpa使用代理建立实现类
public interface SoftDeleteRepository<T, ID> {

	T getEntityById(ID id);

	/**
	 * 希望重写findById方法
	 * @param id
	 * @return
	 */
	T getById(ID id);

}

覆盖默认的deleteById方法,实现软删除

/**
 * 自定义的公共仓储的实现
 *
 * @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);
		}
	}

}

需要实现软删除的仓库接口上,继承这个接口即有这个软删除的能力

/**
 * 用户仓储
 *
 * @author lind
 * @date 2025/7/15 15:56
 * @since 1.0.0
 */
public interface UserEntityRepository extends SoftDeleteRepository<UserEntity, String>,
		JpaRepository<UserEntity, String>, JpaSpecificationExecutor<UserEntity> {

}
posted @ 2026-03-03 16:41  张占岭  阅读(5)  评论(0)    收藏  举报