java - 在 Spring Boot JPA 中使用 Hibernate 过滤器

标签 java spring hibernate spring-boot

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

在关注 this guide 之后我有以下内容:

@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);
    }
}

但是,我真的不明白如何在使用 Spring Data JPA 时切换此过滤器。我正在像这样获取我的父实体:
public SystemNode getSystem(UUID uuid) {
    return systemRepository.findByUuid(uuid)
        .orElseThrow(() -> new EntityNotFoundException("Could not find system with id " + uuid));
}

而这个方法又会调用 Spring 支持的存储库接口(interface):
public interface SystemRepository extends CrudRepository<SystemNode, UUID> {

    Optional<SystemNode> findByUuid(UUID uuid);

}

我怎样才能让这个过滤器与 Spring 一起很好地发挥作用?我想在需要时以编程方式激活它,而不是全局激活它。在某些情况下,忽略过滤器是可行的。

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

最佳答案

更新及解决方案

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

@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;
}

我在 FilterDef 中也输入了错误的类型注解:
@FilterDef(name="dateFilter", parameters=@ParamDef( name="fromDate", type="timestamp" ) )

我从 date 更改至timestamp .

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

谢谢!

关于java - 在 Spring Boot JPA 中使用 Hibernate 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49752429/

相关文章:

java - 如何创建 Google Guava 的 TreeMultimap 的同步版本

java - 为后台进程编写测试(如后台作业)

java - hibernate spring 不关闭连接

java - 如何在 Java 应用程序中播放 .SWF?

java - 服务器套接字文件传输

spring - org.springframework.aop.framework.Cglib2AopProxy WARN - 无法代理方法

java - 在 Hibernate 中存储坐标 (x,y) 的首选方式是什么?

java - 我是否有 Hibernate 缓存或映射错误?

Javafx TableView 显示问题

java - 基于Spring的应用程序无法初始化entityManagerFactory,NoSuchMethodError