0

Well, first: I found this question:

What to use: JPQL or Criteria API?

and from other searches I suppose that the only benefit of criteria api is that can check the query and, if it isn't correct, returns a compiler error. Is it right? If no, which are the advantage and disavantage from using JPQL or Criteria Api?

P.S.: The question is born after this other question:

https://stackoverflow.com/questions/8342955/error-in-criteriaquery and the difficult that I'm finding to resolve that problem when I do the correct method using JPQL in 20 minutes...

Community
  • 1
  • 1
Filippo1980
  • 2,745
  • 5
  • 30
  • 44
  • possible duplicate of [What to use: JPQL or Criteria API?](http://stackoverflow.com/questions/3858406/what-to-use-jpql-or-criteria-api) – Don Roby Dec 06 '11 at 11:58
  • @ don roby : as I wrote, I read that question but in that case the question was specific, I would an answer more generic... – Filippo1980 Dec 06 '11 at 16:48
  • that question looks pretty generic to me, and has an accepted answer that is quite good and pretty general as well. – Don Roby Dec 06 '11 at 17:00

1 Answers1

0

I think what you are asking is when would you consider a Criteria Query. I will further assume you are using an Application Server.

The Criteria API exists to allow for the construction of dynamic SQL queries in a type-safe manner that prevents SQL injection. Otherwise you would be concatenating SQL strings together which is both error prone and a security risk: i.e. SQL Injection. That would be the only time you would want to use the Criteria API.

If the query remains basically the same but need only accept different parameters you should use annotated @NamedQueries which are simpler, precompiled, can be cached within the secondary cache and validated during server startup.

That's basically the the rule of thumb concerning Criteria Queries versus @NamedQueries. In my experience rarely do you require the Criteria API but it is good that it exists for those rare times it is required.

Hope this helps.

sagneta
  • 1,546
  • 18
  • 26