仅在某些实体关系中禁用附加条件

Disable additional criteria only in some entity relations

我正在制作一个基于 JPA/EclipseLink 的应用程序,我在实体层次结构的根 class 中使用 @AdditionalCriteria 实现了软删除功能(所有实体都继承自此)。

我的问题是现在,我需要创建一个包含与其他实体的多种关系的特殊实体;我需要恢复所有相关实体,包括软删除的实体。有可能只在这个特殊实体与 EclipseLink 的关系中禁用 @AdditionalCriteria 吗?如果没有,执行此操作的最佳选择是什么?我的代码如下所示:

////Example of my top entity class (all others inherit from this)
@AdditionalCriteria("this.deleted = false")
public abstract class TopHierarchyClass {
  ···
  @Column(name = "deleted")
  protected boolean deleted = false;
  ···
}

//Example of entity that needs recover all relationed entities including soft deleted
@Entity
@Table(name = "special_entities")
public class SpecialEntity extends EntityBase {
  ···
  @JoinColumn(name = "iditem", referencedColumnName = "id")
  @ManyToOne(fetch = FetchType.LAZY)
  private Item item;
  ···
}

@Entity
@Table(name = "items")
public class Item extends EntityBase {
  ···
}

提前致谢

为同一个 table 创建一个没有 @AdditionalCriteria 的新实体。这样您就可以从 table 中检索所有记录,而无需应用额外的过滤器。

例如:

public interface Person {
    Long getId();
    void setId(Long id);
    Date getDeletedAt();
    void setDeletedAt(Date deletedAt);
}

@MappedSupperclass
public class PersonEntity implements Person {
    @Id
    private Long id;
    private Date deletedAt;

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public Date getDeletedAt() { return deletedAt; }
    public void setDeletedAt(Date deletedAt) { this.deletedAt = deletedAt; }
}

@Entity
@Table(name = "people")
@AdditionalCriteria("this.deletedAt is null")
public class ActivePersonEntity extends PersonEntity {
}

@Entity
@Table(name = "people")
public class RawPersonEntity extends PersonEntity {
}

public class PeopleRepository {
    @PersistenceContext
    private EntityManager em;

    public List<Person> all() {
       return all(false);
    }

    public List<Person> all(boolean includeSoftDeleted) {
       if (!includeSoftDeleted) {
           return em.createQuery("select p from ActivePersonEntity p", ActivePersonEntity.class).getResultList();
       } else {
           return em.createQuery("select p from RawPersonEntity p", RawPersonEntity.class).getResultList();
       }
    }
}

此外,如果您的 @AdditionalCriteria 在超级 class 中,您可以通过在子 class 中声明一个新的空 @AdditionalCriteria 来覆盖它:

You can define additional criteria on entities or mapped superclass. When specified at the mapped superclass level, the additional criteria definition applies to all inheriting entities, unless those entities define their own additional criteria, in which case those defined for the mapped superclass are ignored.

@AdditionalCriteria doc