spring-data-jpa 中的交叉连接 [英] cross join in spring-data-jpa
本文介绍了spring-data-jpa 中的交叉连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有两个实体
@Entity
public class Event{
...
@ManyToMany(fetch = FetchType.LAZY)
private Set<EventGroup> eventGroups;
}
@Entity
public class EventGroup {
...
@ManyToMany(fetch = FetchType.LAZY)
private Set<Event> events;
}
我需要获取具有给定 ID 的 EventGroups 的 Events.使用 spring 数据 CrudRepository.
I need to get Events which has EventGroups with given ids. Using spring data CrudRepository.
@Repository
public interface EventRepository extends CrudRepository<Event, Long>, JpaSpecificationExecutor {
}
我打电话
eventRepository.findAll(buildSpecification(filter);
这就是我构建规范的方式:
This is how i build specification:
private Specification<Event> buildSpecification(final EventFilter filter) {
final Specification<Event> specification = new Specification<Event>() {
@Override
public Predicate toPredicate(Root<Event> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
root = criteriaQuery.distinct(true).from(Event.class);
Predicate predicate = cb.conjunction();
if (filter.getEventGroupIds() != null) {
Join<Event, EventGroup> join = root.join(Event_.eventGroups);
predicate.getExpressions().add( join.get(EventGroup_.id).in(filter.getEventGroupIds()) );
}
return criteriaQuery.where(predicate).getRestriction();
}
};
return specification;
}
但是结果查询是
SELECT DISTINCT
event0_.id AS id1_1_,
event0_.createdAt AS createdA2_1_,
event0_.date AS date3_1_,
event0_.image_id AS image_id6_1_,
event0_.moderated AS moderate4_1_,
event0_.name AS name5_1_,
event0_.owner_id AS owner_id7_1_
FROM Event event0_
CROSS JOIN Event event1_
INNER JOIN Event_EventGroup eventgroup2_ ON event1_.id = eventgroup2_.Event_id
INNER JOIN EventGroup eventgroup3_ ON eventgroup2_.eventGroups_id = eventgroup3_.id
WHERE eventgroup3_.id IN (15)
这个交叉连接破坏了一切.
This cross join corrupt everything.
我该怎么办?可能还有其他方法获得它吗?
What should i do? May be there is another way to get it?
推荐答案
已解决
private Specification<Event> buildSpecification(final EventFilter filter) {
final Specification<Event> specification = new Specification<Event>() {
@Override
public Predicate toPredicate(Root<Event> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
cq.distinct(true);
Predicate predicate = cb.conjunction();
if (filter.getEventGroupIds() != null) {
Join<Event, EventGroup> join = root.join(Event_.eventGroups);
predicate.getExpressions().add(join.get(EventGroup_.id).in(filter.getEventGroupIds()) );
}
return predicate;
}
};
return specification;
}
这篇关于spring-data-jpa 中的交叉连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文