Spring Data JPA: How to use objects with the @Query annotation?

Viewed 324

Consider the following JpaRepository.

interface ExpectedLossRepository : JpaRepository<ExpectedLoss, Long> {

    fun getByDealId(dealId: Long): ExpectedLoss

    @Query("select el from ExpectedLoss el where el.dealId = ?1.dealId and ...")
    fun getByExtendedTerm(@Param("extended_term") term: ExtendedTerm): ExpectedLoss        
}

The first function lets me query for ExpectedLoss entities by dealId, so far so good. But now I need to build a complex query and therefor don't want pass all required primitives, but instead an instance of an object.

This query doesn't work. How do I reference the passed object?

@Query("select el from ExpectedLoss el where el.dealId = (?1).dealId and ...")
1 Answers

I figured it out in the meantime. The correct syntax is:

interface ExpectedLossRepository : JpaRepository<ExpectedLoss, Long> {

    @Query("select el from ExpectedLoss el where el.dealId = :#{#term.dealId}")
    fun getByExtendedTerm(@Param("extended_term") term: ExtendedTerm): ExpectedLoss

    fun getByDealId(dealId: Long): ExpectedLoss
}
Related