简体   繁体   中英

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.

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

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_)]

I couldn't find a way to take property value from A or pass param to @Where annotation.

You can use the native query in JPA as follows:

    @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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM