Skip to main content

Don't mess your JPADAO with named queries stuff

Posted by gadominas on January 22, 2008 at 3:45 PM PST

Let's say I have tones of named queries through all my entities. These queries have one/two or more named parameters in conditional expression.
The common way to encapsulate my named query lookup in my JPADAO is something like this:

Query q = %getEntityManager()%.createNamedQuery( %queryName% );
q.setParameter ("someParam", new Date ());
q.setParameter ("anotherParam", true);
q.setParameter ("tired_butAnoterParamX", 666L);
return q.getResultList();

Do we have another way here? What if my named queries are overloaded by entity mapping..

My proposal for myself was to make generic lookup in my base JPADAO, as follows:

1. pass the named query name and named arguments as a array as follows:
%someFactory%.getXJPADAO().executeNamedQuery( "QueryName", param1, param2, .... , paramN);

2. Retrieve the entity type which is associated with the dao.

3. Tokenize the query which we want to execute and build the parameters bind set.

4. Go through parameters bind set and setup the query.

As an example it can be shown as follows:

This example will not cover positional parameters features.

Folks, what do you think. I'm too high from the ground or we have a better way? How you deal with this area?

Related Topics >>


To freddy33: I like your approach. You covered whole CRUD, plus your custom queries. Obviously someone will dig that you will fail when you is forced to debug your code.. or you fail when your named query is overridden by entity mapping with the updated set of parameters.. really I'm not sure which one of the solution is better. "auto-magic" looks better at first glance for me..

Named queries in JPA are an issue indeed. Dealing with this issue I personally ended up with a dynamic proxy calling my named queries via a user declared interfaces. It replace the entity name wrapping issue with strongly typed interface, the name of the query is the method name, and query parameters are method parameters. The code and the description of this small trick is here.

Interesting example you've got there.

Hmmm. I can't seem to make up my mind. I think, it is a bit too much "auto-magic" for me. Guess I haven't seen it as such a big problem in my daos yet :-) I know you shouldn't do up-front optimization, before you now it is a problem. But, ... have you thought about performance here? :-)

Another thing: You might loose some IDE/tool refactoring and stuff. IDEA can recoqnize the JPA apis, and will color a query name in createNamedQuery(...) red, if it doesn't exist. In addition, it will rename them correctly etc. You might miss some of this, if you provide a second api of your own.

Tech Per