之前写过关于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 SoftDeleteRepositoryT, ID { T getEntityById(ID id); /** * 希望重写findById方法 * param id * return */ T getById(ID id); }覆盖默认的deleteById方法实现软删除/** * 自定义的公共仓储的实现 * * param T * param ID */ public class SoftDeleteRepositoryImplT, ID extends SimpleJpaRepositoryT, ID implements SoftDeleteRepositoryT, ID { private final EntityManager entityManager; private final JpaEntityInformationT, ID jpaEntityInformation; ClassT domainType; Logger logger LoggerFactory.getLogger(SoftDeleteRepositoryImpl.class); public SoftDeleteRepositoryImpl(JpaEntityInformationT, 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 SoftDeleteRepositoryUserEntity, String, JpaRepositoryUserEntity, String, JpaSpecificationExecutorUserEntity {