user1516815 user1516815 - 2 months ago 35
Java Question

Load JPA repository queries from a property file

I need to load queries in a repository from a property file. For example, here:

@Repository
public interface StudentRepository extends JpaRepository<Student, Integer> {

@Query(value="SELECT * FROM student where year= :le", native=true)
public List<Student> getStudentsByLevel(@Param("le") int level);

}


I need to load the
"SELECT * FROM student where year= :le"
string from a property file. Is there any way to do it?

Answer

As suggested above I have overcome this problem by using xml configured named queries. Below is the example.

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">

    <persistence-unit name="hibernatePersistenceUnit">

        <!-- <mapping-file>META-INF/jpql/oracle-quries.xml</mapping-file> -->
        <mapping-file>META-INF/jpql/mysql-quries.xml</mapping-file>
    </persistence-unit>
</persistence>

mysql-quries.xml

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="1.0"
    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 ">

    <named-native-query name="Nodecontrol.lockNodeController">
        <query>
            SELECT * FROM student where year= :le
        </query>
    </named-native-query>
</entity-mappings>

In oracle-quries.xml and mysql-quries.xml I have defined all the native queries respectively. When I need to change the query without changing the class file I just need to mention the file name i need to use in persistence.xml.

Comments