将 Hibernate 过滤器与 Spring Boot JPA 结合使用

jok*_*arl 4 java spring hibernate spring-boot

我发现需要通过子类中的属性来限制子集合的大小。

遵循本指南后,我得到以下结果:

@FilterDef(name="dateFilter", parameters=@ParamDef( name="fromDate", type="date" ) )
public class SystemNode implements Serializable {

    @Getter
    @Setter
    @Builder.Default
    // "startTime" is a property in HealthHistory
    @Filter(name = "dateFilter", condition = "startTime >= :fromDate")
    @OneToMany(mappedBy = "system", targetEntity = HealthHistory.class, fetch = FetchType.LAZY)
    private Set<HealthHistory> healthHistory = new HashSet<HealthHistory>();

    public void addHealthHistory(HealthHistory health) {
        this.healthHistory.add(health);
        health.setSystem(this);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我不太明白如何在使用 Spring Data JPA 时切换此过滤器。我正在像这样获取我的父实体:

public SystemNode getSystem(UUID uuid) {
    return systemRepository.findByUuid(uuid)
        .orElseThrow(() -> new EntityNotFoundException("Could not find system with id " + uuid));
}
Run Code Online (Sandbox Code Playgroud)

而这个方法又调用Spring支持的repository接口:

public interface SystemRepository extends CrudRepository<SystemNode, UUID> {

    Optional<SystemNode> findByUuid(UUID uuid);

}
Run Code Online (Sandbox Code Playgroud)

我怎样才能让这个过滤器与 Spring 完美配合?我想在需要时以编程方式激活它,而不是全局激活它。在某些情况下,可以忽略过滤器。

我正在使用 Spring Boot 1.3.5.RELEASE,目前无法更新。

jok*_*arl 6

更新及解决方案

我按照上面评论中的建议尝试了以下操作。

@Autowired
private EntityManager entityManager;

public SystemNode getSystemWithHistoryFrom(UUID uuid) {
    Session session = entityManager.unwrap(Session.class);

    Filter filter = session.enableFilter("dateFilter");
    filter.setParameter("fromDate", new DateTime().minusHours(4).toDate());

    SystemNode systemNode = systemRepository.findByUuid(uuid)
            .orElseThrow(() -> new EntityNotFoundException("Could not find system with id " + uuid));

    session.disableFilter("dateFilter");

    return systemNode;
}
Run Code Online (Sandbox Code Playgroud)

我在注释中也有错误的类型FilterDef

@FilterDef(name="dateFilter", parameters=@ParamDef( name="fromDate", type="timestamp" ) )
Run Code Online (Sandbox Code Playgroud)

我从date改为timestamp

这将返回正确的对象数量,并根据数据库进行验证。

谢谢你!