Execute dynamic query with Spring Data JPA

Viewed 542
@Query(value = "SELECT * FROM H4 WHERE 1")
List getResult();

Instead of the query "SELECT * FROM H4 WHERE 1" I want to put a String variable containing query generated elsewhere.

2 Answers

@Query, like any other annotation, uses a compile time constant to define attributes. You can't define it's value in runtime unless you plan to hack the Spring Data JPA framework.

You should use either Specifications with criteria, Query by example or JPQL to define and execute your dynamic query.

Create constants and set the value as below.

@Query(value = ApplicationConstantClass.QUERY_STRING_CONSTANT)
List getResult();

or Use EntityManager or SessionFactory of hibernate to execute dynamically generated query.

Related