gpt4 book ai didi

java - JPA Criteria API 规范 JOIN 按条件且结果不为空

转载 作者:行者123 更新时间:2023-11-30 02:16:03 24 4
gpt4 key购买 nike

代码示例:

@Entity
public class Event {

@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(...)
private List<Actions> actions;

}


@Entity
public class Action {

@Id
@GeneratedValue
private Long id;
private String name;
private Date date;
@ManyToOne
@JoinColumn(name = "event_id")
private Event event;

}

public class EventSpecification {

public static Specification<Event> findByCriteria(EventSearchCriteria criteria) {

return (root, criteriaQuery, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<>();

criteria.getEventName().ifPresent(name ->
predicates.add(criteriaBuilder.equal(criteriaBuilder.lower(root.get(Event_.name)), name)));

criteria.getDate().ifPresent(date ->
// Need one more Predicat - event.has.actions.with.date.equals.criteria.date
);

return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
};
}
}

问题是:

如何创建谓词 - 仅限具有 Action.date = searchCriteria.date 的操作的事件。我认为这是可能的,但我找不到解决方案。

最佳答案

也许这会帮助你指出正确的方法

criteria.getDate().ifPresent(date -> {
Join join = root.join("actions");
predicates.add(criteriaBuilder.equal(join.get("date"), date);
});

关于java - JPA Criteria API 规范 JOIN 按条件且结果不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48398872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com