我发现需要通过子类中的属性来限制子集合的大小。
在关注 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/