Peter
Peter

Reputation: 29877

Is it good practice to use @NamedQuery for single column selects (J2EE/JPA, Hibernate)

I'm working on J2EE 6 codebase that uses Hibernate as its persistence provider. My experience lies more in Spring and I'm quite new to JPA annotations and similar, but I've noticed a lot of this in all the entity classes, and it surprises me - I thought @NamedQuery were more for complex SQL? Surely these simple selects (and joins that are defined in the hibernate mappings) can be done without writing out the SQL?

In the Entity:
@NamedQueries({
@NamedQuery(name = "DealRaw.findByrawUrl", query = "SELECT d FROM DealRaw d WHERE d.rawUrl = :rawUrl"),
@NamedQuery(name = "DealRaw.findByState", query = "SELECT d FROM DealRaw d WHERE d.state = :state"),
.... etc ....
})

and then

In the Service Class
Query qR=_em.createNamedQuery("DealRaw.findByrawUrl");  //_em is an EntityManager
qR.setParameter("rawUrl", value);
List<DealRaw> dRs=(List <DealRaw>)qR.getResultList();

Upvotes: 3

Views: 3410

Answers (3)

digitaljoel
digitaljoel

Reputation: 26574

As JB Nizet said, in order to find the result set, you're going to have to write the queries somewhere.

One advantage to having them as a NamedQuery (or CriteriaQuery if that's your thing) is that you are protecting yourself against SQL injection. If the query is created on the fly in the code with string concatenation such as String query = "SELECT d FROM DealRaw d WHERE d.rawUrl = '" + rawUrl + "'"; or even using named parameters, some programmer in the future may come along and modify the query in a way that allows SQL injection (as in the example).

Yes, there are ways to use named parameters in a query constructed in code with concatenation, but that doesn't protect you as much as a pre-defined Named Query.

Upvotes: 1

flavio_yama
flavio_yama

Reputation: 313

Why not use Criteria instead of using NamedQuery? Filtering will be a lot easier. In some cases creating the Criteria gets very confusing and hard, however for single column I believe it is the easiest option.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692071

These queries are not SQL queries, but JPQL queries. And you may put any kind of query inside a named query, complex or not.

They all have the same advantages :

  • the JPA engine parses and validates the query at startup time, and may cache the result of the parsing to avoid parsing it again and again.
  • the same query may easily be used at several places in the code (although that would be questionable design)

They all have the same disadvantage, IMO : the query is not defined where it is used, and the code is thus harder to understand.

Whether those queries are named or not, you will have to write these queries to execute them. The only other ways to load entities are to find them using their ID (which is not the case here), or to navigate from one entity to another using associations (which is not the case either).

Upvotes: 2

Related Questions