2017-10-06 34 views
0

我需要通过entity2的ID获取Entity1's如何使用IN语句编写弹簧数据查询?

查询有参数 - 列表号 - 实体2的ID号 。 和两个实体@OneToMany势必

@Entity 
class Entity1 { 
private Integer id; 

private Entity2 entity2; 

--------- 
@OneToMany(cascade = ALL, fetch =FetchType.EAGER) 
@Column 
public Entity2 getEntity2(){ 
return entity2; 

} 

@Entity 
public class Entity2{ 

private Integer id; 

@ManyToOne(FetchType.LAZY) 
private Entity1 entity1; 
} 

我已经工作的代码

@Repository 
public interface Entity1Repository extends JpaRepository<Entity1, Integer> { 

@Query("SELECT c" + 
      " FROM Entity1 c" + 
      " inner JOIN c.entity2 a" + 
      " WHERE a.id IN(?1)") 
    Set<Entity1> findByEntity2Ids(List<Integer> pEntity2_Ids); 
} 

我想用Spring数据

美化查询和喜欢写东西

Set<Entity1> findAllByEntity2In(List<Integer> pChannels); 

,但它不工作现在

我赶上了Enxception:

\造成的:java.lang.IllegalArgumentException异常:参数值元素[2]不匹配预期的类型[com.test.Entity2 (n/a)]

谁知道如何解决?

谢谢!

回答

0

删除查询中的括号。 它应该是这样的:

@Query("SELECT c" + 
      " FROM Entity1 c" + 
      " inner JOIN c.entity2 a" + 
      " WHERE a.id IN ?1") 

为了更好的可读性查询时,您可以选择使用命名参数而不是位置之一。这么说,您的查询可能是这样的:

@Query("SELECT c" + 
      " FROM Entity1 c" + 
      " inner JOIN c.entity2 a" + 
      " WHERE a.id IN :ids") 
    Set<Entity1> findByEntity2Ids(@Param("ids") List<Integer> pEntity2_Ids); 
0

您可以通过列表中执行搜索或设置ENTITY2像

Set<Entity1> findByEntity2In(Set<Entity2> entity2); 

对于由ENTITY2编号找到,你需要编写查询像

@Query("SELECT ent1 FROM Entity1 ent1 INNER JOIN c.entity2 ent2 WHERE ent2.id IN :ids") 
Set<Entity1> findByEntity2Ids(@Param("ids") List<Integer> pEntity2_Ids); 
0

UPD

我找出春d查询ata:

@Repository 
    public interface Entity1Repository extends JpaRepository<Entity1, Integer> { 

    Set<Enity1> findByEntity2In(List<Integer> pEntities2Ids); 

} 
相关问题