Start off by putting the @NamedQuery annotation on your entity class
Then add a corresponding entry to your NamedQueries class along with a comment. You'll notice that the value of the constant is the named attribute we provided to the @NamedQuery annotation above.
The end result of these is that named queries 1) will never be mistyped, and 2) provide handy context help to remind you which parameters need to be added:
Tuesday, October 24, 2006
A Sane Way of Using EJB3 Named Queries
Labels:
best practices,
development,
ejb,
java
Subscribe to:
Post Comments (Atom)
1 comments:
An even better solution is to use an enum. This allows javadoc commenting of the intended usage of each named query as well as comments for any args the named query takes:
/**
* Groups named queries to prevent "magic strings" through the code base.
*/
public static enum Query {
/**
* Finds the birthday for a given person.
* @param personId The id of the Person who's birthday we need.
*/
GET_BIRTHDAY("Person.getBirthday");
private final String namedQuery;
Query(String namedQuery) {
this.namedQuery = namedQuery;
}
@Override
public String toString() {
return namedQuery;
}
}
Post a Comment