Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Externalize native query in Spring data JPA [duplicate]

I am using spring-data JpaRepository. I have the following native query :

@Query(value = "SELECT SUBSTRING_INDEX(u.email, '@', -1) as domain, COUNT(*) as domainCount, r.invite_organization_id"
        + "  FROM srs_users as u,srs_user_registrations as r where u.user_id=r.user_id and r.invite_organization_id=:orgId"
        + "  GROUP BY "
        + "SUBSTRING_INDEX(u.email, '@', -1) ORDER BY domainCount DESC", nativeQuery = true)
List<Object[]> countTopDomain(@Param("orgId") String orgId );

Can we externalize the above native query in jpa-named-queries.properties just like other named queries.

like image 824
souvikc Avatar asked Apr 12 '26 07:04

souvikc


2 Answers

You can use JPA Named queries. But I'm afraid that is not exactly what you are looking for. Other than that there is no support of externalizing SQL statements.

like image 200
Jens Schauder Avatar answered Apr 16 '26 16:04

Jens Schauder


At resources create a folder META-INF. At META-INF create a default file jpa-named-queries.properties

In this file put your query at any unique key. Say,

chk.test1=SELECT SUBSTRING_INDEX(u.email, '@', -1) as domain, COUNT(*) as domainCount, r.invite_organization_id FROM srs_users as u, srs_user_registrations as r where u.user_id=r.user_id and r.invite_organization_id=:orgId GROUP BY SUBSTRING_INDEX(u.email, '@', -1) ORDER BY domainCount DESC

To use this use below code:

@Query(name = "chk.test1", nativeQuery = true) List<Object[]> countTopDomain(@Param("orgId") String orgId );

like image 36
Spandan Avatar answered Apr 16 '26 16:04

Spandan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!