views:

492

answers:

1

What is the right way do validate a jpa query programmatically. Hibernate validates all annotation based named queries on entities. But how can I call this validation routine on programmatically builded jpa queries, to check for errors?

@Entity
public class Foo {
@Id
public int id;

public String name;

}
main(...) {
    Query q = getEntityManager().createQuery("select e from " + Foo.class.getName() + " e where e.name = 'x' ");
    // validate q here
}
+2  A: 

Don't. Integration test the hell out of your code, using a real database with the same schema as your production environment.

Think about it: if you create a malformed query, that's a programming bug. What are you going to do with the information? Tell the user that a JPA query is malformed? All you can realistically do is log the error and tell the user "something bad happened". You'll know it's a malformed query when you check the logs later anyway...

Edit

It might also be worth investigating the createQuery() call by feeding it bad data - the javadoc here suggests that it can throw a HibernateException, and I'm not sure what it could do with a string other than validate it...

Dan Vinton
i just want validate my programmaticly generated queries, just like hibernate does it for @namedquery. If a error is found the program must of course shutdown. Where i do the check is not the question here, the How is.
KlausMeier
@KlausMeier - if you look here: https://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html#createQuery(java.lang.String), you'll see that the createQuery() method can throw an exception. It might well already be validating for you. Feed a broken query in and see what happens?
Dan Vinton