2015-04-30 72 views
1

我有3个关系中的实体。以下是我班的一个简单的例子:如何查询具有多对多关系的实体?

@Entity 
public class Action {} 

@Entity 
public class Instance { 

    @ManyToMany 
    private Set<Action> actions; 

    @ManyToMany 
    private Set<CadSystem> cadSystems; 

} 

@Entity 
public class CadSystem {} 

我如何可以查询属于特定ActionCadSystem所有Instance S' 比如我希望做一个JpaRepository如下:

public interface InstanceRepository extends JpaRepository<Instance, Long> { 

    List<Instance> findByActionAndCadSystem(Action action, CadSystem cadSystem); 

} 

但是,这是不可能的,因为Instance没有名为actioncadSystem领域。 我认为有以下将工作:

public interface InstanceRepository extends JpaRepository<Instance, Long> { 

    List<Instance> findByActionsAndCadSystems(Set<Action> actions, Set<CadSystem> cadSystems); 

} 

但在这种情况下,我总是要创建一个新的Set只有一个元素。

回答

0

使用查询。此外,请注意,由于关联是多对多的,因此此查询可能会返回多个操作:

select i from Instance i 
join i.actions action 
join i.cadSystems cadSystem 
where action = :action 
and cadSystem = :cadSystem 
相关问题