Spring data jpa, externalizing native queries

After many efforts and tries found the solution.

1) create the xml file (with any name) in resources folder of your project. Say testSQL.xml inside resources /query

2) follow the xml standard of 'orm.xml' in testSQL.xml, this copy paste the header and create the tags of,

<?xml version="1.0" encoding="UTF-8" ?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
version="1.0">
<named-native-query>
</named-native-query>
</entity-mapping>

3) in this xml create the tag with named-native-query tag.

<named-native-query name="XyzEntity.methodName">
<query>
<! [CDATA[
Your native query
] ] >
</query>
</named-native-query>

Note - > multiple such native named query tags can be added and all of them must reside between

<entity-mapping> </entity-mapping>

4) "XyzEntity" mentioned in name tag in above step, should have a Jpa repository and in that repository we should have method with the same name as the tag. I. E.

public interface XyzRepo extends JpaRepository <XyzEntity, Long> {
Tuple methodName() ; 

}

5) add the testSQL.xml in application property file as below

spring.jpa.mapping-resources = query/testSQL.xml

N then you can call this method normal spring way.

Kindly let me know if someone is stuck on this and need detail solution.


You can externalize de value, which is the query itself. Inside the src/main/resources, create a folder called META-INF. Inside it, create a file called jpa-named-queries.properties.

Suppose your entity is called Customer and the table is TBL_CUSTOMER.

When you keep the query inside the code, on your repository, you have the code you wrote. You can externalize it this way:

CustomerRepository.java

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {

    @Query(nativeQuery = true) 
    public List<String> findNameNative();

}

jpa-named-queries.properties

Customer.findNameNative=\
SELECT C.NAME \
FROM TBL_CUSTOMER C \
WHERE CONDITIONS

Names must match and you must use \ for line breaks.


Under resources create META-INF/jpa-named-queries.properties. In this file define your queries this way: MyEntity.fetchEntityBySomething=select name from Customer

I have not tried native queries however, usual queries would work this way.

However, check this out: https://github.com/gasparbarancelli/spring-native-query