簡體   English   中英

如何在 Spring 啟動 JPA 中加入 OneToMany 與復雜的 Where 條件?

[英]How to join OneToMany in Spring boot JPA with a complex Where condition?

考慮一個在 class 上的@Entity ,它具有一個 id 和一個類型,該類型具有一個列表,該列表使用另一個實體上的連接操作。

@Entity
class A {

    @Id
    @Column
    Long id;
    
    @Column
    String typeA;
    
    @OneToMany
    @JoinColumn(name = "ref_id")
    // here a where condition
    List<B> listB;
    
}

@Entity
class B {
   @Id
   @Column
   Long id;

   @Column
   String typeB;

   @Column
   Long ref_id;
}

用於填充 listB 的 SQL 版本是 -

SELECT * FROM B JOIN A ON B.id = A.ID WHERE B.typeB = CONCAT(A.typeA,'_A_')

所以 A (id: 1, typeA: xx) 將鏈接到 b[(id:2, typeB: xx_A_),(id:3,typeB: xx_A_)] 和 A (id: 1, typeA: yy) 將鏈接到 b[(id:2, typeB: yy_A_),(id:3,typeB: yy_A_)]

我找不到從 A 獲取屬性值或將參數傳遞給 @Where 注釋的方法。

您可以使用 JPA 中的原生查詢,如下所示:

    @Query(value = "your SQL query", nativeQuery = true)
    public List<B> getCustomBList();

這必須是:

@Repository
public interface BRepository extends JpaRepository<B, Long> { }

我不太確定您的 SQL 查詢但是是的,您可以在自定義查詢中使用 @Param,這個問題已經在這里得到解答How can I use parameter's method in @Query annotation

這是您可以使用的方法,這已經在上面的問題中說明了,我在這里說明了供您參考。

@Query("select u from User u where u.firstname = ?#{#customer.firstname}")
List<User> findUsersByCustomersFirstname(@Param("customer") Customer customer);

暫無
暫無

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

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