在Spring数据JPA中外部化本机查询

时间:2018-06-27 09:29:50

标签: jpa spring-data-jpa

我正在使用spring-data JpaRepository。 我有以下本地查询:

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

是否可以像其他命名查询一样,在jpa-named-queries.properties中外部化上述本机查询。

2 个答案:

答案 0 :(得分:1)

You can use JPA Named queries。但是,恐怕这并不是您想要的。除此之外,不支持外部化SQL语句。

答案 1 :(得分:1)

在资源处创建一个文件夹 META-INF。 在 META-INF 创建一个默认文件 jpa-named-queries.properties

在此文件中,将您的查询放在任何唯一键上。说,

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和 r.invite_organization_id=:orgId GROUP BY SUBSTRING_INDEX(u.email, '@', -1) ORDER BY domainCount DESC

要使用此代码,请使用以下代码:

@Query(name = "chk.test1", nativeQuery = true) List countTopDomain(@Param("orgId") String orgId );