大家好,又见面了,我是你们的朋友全栈君。
为了避免每次在查询的时候加上是否删除字段,做了一下封装。
@NoRepositoryBean @RepositoryRestResource(exported = false) public interface BaseRepository<T extends BaseEntity, IdT extends Long> extends JpaRepository<T, IdT> { @Query( value = "update #{#entityName} set deletedAt=current_timestamp where id = ?1 " + "and deletedAt is null") @Transactional @Modifying void delete(IdT id); @Override @Transactional default void delete(T entity) { delete((IdT) entity.getId()); } @Transactional default void delete(Iterable<? extends T> entities) { entities.forEach(entitiy -> delete((IdT) entitiy.getId())); } @Override @Query(value = "update #{#entityName} set deletedAt=current_timestamp where deletedAt is null ") @Transactional @Modifying void deleteAll(); @Query( value = "update #{#entityName} set deletedAt=current_timestamp where id in ?1 " + "and deletedAt is null ") @Transactional @Modifying void deleteInBatch(List<IdT> ids); }
@NoRepositoryBean 使用了该注解的接口不会被单独创建实例,只会作为其他接口的父接口而被使用。 deletedAt 是否删除字段
@MappedSuperclass @Data public abstract class BaseEntity { private Timestamp deletedAt; public abstract Long getId(); }
@MappedSuperclass 通过这个注解,我们可以将该实体类当成基类实体,它不会隐射到数据库表,但继承它的子类实体在隐射时会自动扫描该基类实体的隐射属性,添加到子类实体的对应数据库表中。
@Data @Entity @Table(name = "indeed_api_keys") @Where(clause = "deleted_at is null") @NoArgsConstructor public class IndeedApiKey extends BaseEntity implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String key; private static final long serialVersionUID = 1866497302444576352L; }
实体继承BaseEntity,并加上 @Where(clause = “deleted_at is null”)
public interface EmailMessageRepository extends BaseRepository<EmailMessage, Long> { List<EmailMessage> findAllByApplicationId(Long applicationId); @Query( value = "SELECT * FROM email_messages e WHERE e.deleted_at IS NULL AND " + "lower(?1)=lower(e.email_hash) ORDER BY e.created_at DESC", nativeQuery = true) List<EmailMessage> findByEmailHash(String emailHash); }
Repository继承BaseRepository
这样配置之后,若使用jpa默认的查询,就会自动加上 deleted_at is null的过滤条件。但当你重写jpa默认的查询机制,还是需要手动加上deleted_at is null的过滤条件。
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/137129.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...