Question

Is there a simple way (through Java code) to verify if the HQL is syntactically correct?

One way is certainly to execute it and catch the exception. But I want to avoid firing the query.

In my case, the HQL is generated on the fly depending on user's selection and sometimes the user may even enter it manually. Hence, I want to verify if the HQL is in the correct form.

Was it helpful?

Solution

Giving a query like

final String theQuery = "update Person p set ps.count = (p.count + ?) where id = ?";

Fast way, but need to add listener and not precise

HqlParser parser = HqlParser.getInstance(theQuery);
parser.statement();
parser.getAST() /*if null probably an error occurred*/

More precise way

final SessionFactoryImplementor sfi = (SessionFactoryImplementor) sf;
final QueryTranslatorFactory qtf = sfi.getSettings().getQueryTranslatorFactory();
qtf.createQueryTranslator("myQuery", theQuery, new HashMap(), sfi).compile(new HashMap(), false);

OTHER TIPS

If your only want to ensure that the hql is properly formed, then you I suggest you just wrap your statement in a transaction, then try to execute the statement. Of course it will throw an error if the HQL is invalid, catch that exception then perform rollback to prevent any changes to your DB.

Session sess = factory.openSession();
Transaction tx;

try {
    tx = sess.beginTransaction();
    //execute the hql. will throw an error if not a valid one
    //...

    //commit if hql is not malformed
    tx.commit();
}
catch (Exception e) {
    if (tx!=null) tx.rollback(); //hql not valid. rollback
    throw e;
}
finally {
    sess.close();
}

In my development, there are a lot of Entity, OR mapping and Name queries. They simplest way is I use Transaction to check there are whether correct or not.

I use as below in JPA. I am sure there might be a way also Hibernate and HQL.

public static void main(String args[]) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPA");
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    em.getTransaction().commit();
    em.close();
    emf.close();
}

Console will show the missing state/error. If your development have incorrect process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top