Reputation: 971
My Springboot application has orm.xml file in my WEB-INF folder. I have few named native queries in the orm.xml file.
I want to add a where condition in the query based on the values in the parameter to the query.
I am looking for some thing like this:
<named-native-query name="MyReport.countInventory">
<query>
SELECT COUNT(*) AS COUNT
FROM
Inventory
WHERE
<if :date>
add_date = :date
</if>
</query>
</named-native-query>
Upvotes: 0
Views: 686
Reputation: 81998
This is not possible with JPA. It just allows straight-forward SQL statements without any conditional processing.
In many cases, one can actually implement the required conditional logic in SQL itself as Turo described in his/her comment.
Since you are seeming to be using Spring Data JPA you can also use Specifications
to dynamically create conditions.
Another alternative would be to use MyBatis which allows constructing SQL statements in a way similar to what you outline in your question. The following example is taken from http://www.mybatis.org/mybatis-3/dynamic-sql.html
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
Upvotes: 1