簡體   English   中英

如何使用IN語句編寫spring數據查詢?

[英]How can I write spring data query with IN statement?

我需要通過Entity2的ID來獲取Entity1

查詢有參數-列表編號-實體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 Data美化查詢

並寫一些像

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

但現在不起作用

我陷入了困惑:

\\原因:java.lang.IllegalArgumentException:參數值元素[2]與預期的類型[com.test.Entity2(n / a)]不匹配

誰知道如何解決?

謝謝 !

UPD

我發現了對Spring Data的查詢:

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

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

}

從查詢中刪除括號。 它看起來應該像這樣:

@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);

您可以按列表或Entity2的集合進行搜索,例如

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

為了通過Entity2 Id查找,您需要編寫如下查詢

@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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM