Is there a way with spring data jdbc avoid n+1 issue?

Viewed 409

When I run this query, I experience n+1 issue where data JDBC fetches all the related entities of the campaign objects. Is there any way to avoid this using data JDBC?

@Query(
    """
  SELECT campaign.*
  FROM campaign
           JOIN targeting ON campaign.targeting_id = targeting.id
  WHERE (
    CASE
        WHEN campaign.applications_close_date IS NOT NULL
            THEN NOW() BETWEEN campaign.start_date AND campaign.applications_close_date
        WHEN campaign.end_date IS NOT NULL
            THEN NOW() BETWEEN campaign.start_date AND campaign.end_date
        ELSE NOW() >= campaign.start_date
        END
    )
  AND NOT EXISTS
    (
    SELECT *
     FROM application
     WHERE application.campaign = campaign.id
      AND application.influencer = :influencerId 
    )
  """
  )
  fun findAllMatchingByInfluencerId(
    influencerId: Long,
    country: String?
  ): List<Campaign>
1 Answers

Yes, you can.

If you don't need the referenced entities you should use a class that doesn't have those properties as a return value.

If you actually want those referenced entities, but have a more efficient way to construct the entity with its references you may specify your own ResultSetExtractor or RowMapper in the @Query annotation.

Related