简体   繁体   English

如何在 Spring 启动 JPA 中加入 OneToMany 与复杂的 Where 条件?

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

Consider an @Entity over a class having an id and a type which has a list which comes using a join operation on another entity.考虑一个在 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;
}

the SQL version to populate the listB is -用于填充 listB 的 SQL 版本是 -

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

so A (id: 1, typeA: xx) will be linked to b[(id:2, typeB: xx_A_),(id:3,typeB: xx_A_)] and A (id: 1, typeA: yy) will be linked to b[(id:2, typeB: yy_A_),(id:3,typeB: yy_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_)]

I couldn't find a way to take property value from A or pass param to @Where annotation.我找不到从 A 获取属性值或将参数传递给 @Where 注释的方法。

You can use the native query in JPA as follows:您可以使用 JPA 中的原生查询,如下所示:

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

And this must be into:这必须是:

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

I'm not quite sure about your SQL query but Yes you can use @Param in your custom queries,this question is already answered here How can I use parameter's method in @Query annotation我不太确定您的 SQL 查询但是是的,您可以在自定义查询中使用 @Param,这个问题已经在这里得到解答How can I use parameter's method in @Query annotation

Here is how you can use, this is already stated in above question I have stated here for your reference.这是您可以使用的方法,这已经在上面的问题中说明了,我在这里说明了供您参考。

@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