Spring Data Rest Association GET覆盖

时间:2019-03-01 18:07:37

标签: hibernate spring-boot jpa spring-data spring-data-rest

好的,这个问题的答案可能是在春季文档herehere中,但是我找不到它。 我正在尝试实施软删除。 到目前为止,一切正常。除非我通过关联获得记录。

示例: http://localhost:8080/api/accounts返回正确的帐户列表(不显示is_deleted = true的任何帐户)

http://localhost:8080/api/addresses返回正确的地址列表(不显示is_deleted = true处的任何地址)

但是当我按下http://localhost:8080/api/accounts/3c84cdb1-6a01-4364-a60b-305afc521440/addresses时,我会得到所有地址的列表。即使是is_deleted = true

这是我自定义的baseRepository:


@NoRepositoryBean
public interface BaseRepository<T extends BaseEntity, ID> extends JpaRepository<T,ID>{
    void obliterateEntity(T entity);


    @Override
    @Transactional(readOnly = true)
    @Query("select e from #{#entityName} e where e.isDeleted = false")
    Page<T> findAll(Pageable pageable);

    @Override
    @Transactional(readOnly = true)
    @RestResource(exported=false)
    @Query("select e from #{#entityName} e where e.isDeleted = false")
    List<T> findAll(Sort var1);

    @Override
    @Transactional(readOnly = true)
    @RestResource(exported=false)
    @Query("select e from #{#entityName} e where e.isDeleted = false")
    List<T> findAllById(Iterable<ID> var1);

    @Override
    @Transactional(readOnly = true)
    @RestResource(exported=false)
    @Query("select e from #{#entityName} e where e.isDeleted = false")
    List<T> findAll();

    @Override
    @Transactional(readOnly = true)
    @RestResource(exported=false)
    @Query("select e from #{#entityName} e where e.isDeleted = false and e.id = ?1")
    Optional<T> findById(ID var1);

    @Query("update #{#entityName} e set e.isDeleted=true where e.id = ?1")
    @Transactional
    @Modifying
    void delete(UUID id);

    @Override
    @Transactional
    default void delete(T entity) {
        delete(entity.getId());
    }
}

问题: 通过关联链接获取删除的记录时,我需要重写哪些方法?

p.s。我也尝试这样做,而不是覆盖功能:

@SQLDelete(sql =
        "UPDATE address " +
                "SET is_deleted = true " +
                "WHERE id = ?")
@Loader(namedQuery = "findAddressById")
@NamedQuery(name= "findAddressById", query =
        "SELECT add " +
                "FROM Address add " +
                "WHERE " +
                "add.id = ?1 AND " +
                "add.isDeleted = false")
@Where(clause = "is_deleted = false")
public class Address extends BaseEntity {

但是,这需要在每个实体中执行相同的操作。它还具有其他实现问题。

我想我在进行软删除时遇到了麻烦。因此,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

您将需要在关联上添加@Where

public class Account extends BaseEntity {

    @OneToMany
    @Where(clause = "is_deleted = false")
    private Set<Address> addresses;
}

您添加到@Where的{​​{1}}仅对直接加载地址有影响(鉴于您已定义要加载数据的查询,这似乎是多余的)。

请参阅第4节:

https://www.baeldung.com/hibernate-dynamic-mapping