Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should a person use native queries with JPA 2.0 instead of JPQL or CriteriaBuilder?

I am very confused about when and when not to use native queries in JPA 2.0. I was under the impression that using native queries could cause me to get out of sync with the JPA cache. If I can accomplish the same thing with a JPQL or CriteriaBuilder query, is there any good reason to use a native query? Similarly, is there any danger in using a native query if I can accomplish the same thing with JPQL or CriteriaBuilder? And finally, if there is a danger in using a native query as far as getting out of sync with the JPA cache, would the same danger exist in executing an equivalent query with JPQL or CriteriaBuilder?

My philosophy has been do avoid native queries, but surely there are times where they are necessary. It seems to me that if I can do it with JPQL or CriteriaBuilder, then I should.

Thanks.

like image 778
user1148956 Avatar asked Mar 03 '12 14:03

user1148956


People also ask

Should we use native query in JPA?

JPQL is the most commonly used query language with JPA and Hibernate. It provides an easy way to query data from the database. But it supports only a small subset of the SQL standard, and it also does not support database-specific features. If you want to use any of these features, you need to use a native SQL query.

What is the difference between native query and JPA query?

In JPA, you can create a query using entityManager. createQuery() . You can look into API for more detail. Native query refers to actual sql queries (referring to actual database objects).

Why do we use JPQL?

It is used to create queries against entities to store in a relational database. JPQL is developed based on SQL syntax. But it won't affect the database directly. JPQL can retrieve information or data using SELECT clause, can do bulk updates using UPDATE clause and DELETE clause.


1 Answers

I agree with your philosophy.

The main problem with native queries, IMHO, is the maintainability. First of all, they're generally more complex and longer than JPQL queries. But they also hardcode table and column names, rather than using class and property names.

JPQL queries are already problematic when refactoring, because they hard-code class and property names in Strings. But native queries are even worse, because they hard-code table and column names everywhere.

I don't think native select queries are a problem regarding the cache. Native update, insert and delete queries are a problem, though, because they modify data behind the back of the first and second-level cache. So these might become stale.

Another problem is that your native queries could use a syntax that is recognized by one database but not by another, making the application harder to migrate from one database to another.

like image 95
JB Nizet Avatar answered Oct 08 '22 03:10

JB Nizet