[英]How to query for entities with many-to-many relationships?
I have 3 entities that are in relationship. 我有3个有关联的实体。 The following is a simplified example of my classes: 以下是我的课程的简化示例:
@Entity
public class Action {}
@Entity
public class Instance {
@ManyToMany
private Set<Action> actions;
@ManyToMany
private Set<CadSystem> cadSystems;
}
@Entity
public class CadSystem {}
How can I query for all Instance
s that belong to a specific Action
and CadSystem
? 如何查询属于特定Action
和CadSystem
所有Instance
? For example I would like to do the following in a JpaRepository
: 例如,我想在JpaRepository
执行以下JpaRepository
:
public interface InstanceRepository extends JpaRepository<Instance, Long> {
List<Instance> findByActionAndCadSystem(Action action, CadSystem cadSystem);
}
But this is not possible because Instance
has no fields named action
and cadSystem
. 但这是不可能的,因为Instance
没有名为action
和cadSystem
字段。 I think the following would work: 我认为以下方法会起作用:
public interface InstanceRepository extends JpaRepository<Instance, Long> {
List<Instance> findByActionsAndCadSystems(Set<Action> actions, Set<CadSystem> cadSystems);
}
But in this case I would always have to create a new Set
with only one element. 但是在这种情况下,我将总是不得不创建一个只有一个元素的新Set
。
Use a query. 使用查询。 Also, note that since the associations are many-to-many, this query might return several actions: 另外,请注意,由于关联是多对多的,因此此查询可能返回几个操作:
select i from Instance i
join i.actions action
join i.cadSystems cadSystem
where action = :action
and cadSystem = :cadSystem
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.