网站首页 全球最实用的IT互联网站!

人工智能P2P分享Wind搜索发布信息网站地图标签大全

当前位置:诺佳网 > 软件工程 > 后端开发 > Java >

springboot~jpa优雅的软删除能力

时间:2026-03-03 16:41

人气:

作者:admin

标签:

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

之前写过关于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);

}

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

}

作者:仓储大叔,张占岭,
荣誉:微软MVP
QQ:853066980

支付宝扫一扫,为大叔打赏!

温馨提示:以上内容整理于网络,仅供参考,如果对您有帮助,留下您的阅读感言吧!
相关阅读
本类排行
相关标签
本类推荐

CPU | 内存 | 硬盘 | 显卡 | 显示器 | 主板 | 电源 | 键鼠 | 网站地图

Copyright © 2025-2035 诺佳网 版权所有 备案号:赣ICP备2025066733号
本站资料均来源互联网收集整理,作品版权归作者所有,如果侵犯了您的版权,请跟我们联系。

关注微信