bookmark

The best way to write a Spring Data Exists Query - Vlad Mihalcea


Description

["slug" being an entity attribute] Spring Data offers an existsBy query method, which we can define in the PostRepository, as follows: 1 2 3 4 5 6

@Repository public interface PostRepository extends JpaRepository<Post, Long> {

boolean existsBySlug(String slug);

}

[another] option to emulate existence is using a CASE WHEN EXISTS native SQL query: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

@Repository public interface PostRepository extends JpaRepository<Post, Long> {

@Query(value = &quot;&quot;&quot;
    SELECT
        CASE WHEN EXISTS (
            SELECT 1
            FROM post
            WHERE slug = :slug
        )
        THEN 'true'
        ELSE 'false'
        END
    &quot;&quot;&quot;,
    nativeQuery = true
)
boolean existsBySlugWithCase(@Param(&quot;slug&quot;) String slug);

}

Preview

Tags

Users

  • @jil

Comments and Reviews