简体   繁体   中英

How to convert hql to sql and apply filters on it?

I call this method to convert hql query to sql:

public String toSql(String hqlQueryText) {
    if (hqlQueryText != null && hqlQueryText.trim().length() > 0) {
        QueryTranslatorFactory translatorFactory = new ASTQueryTranslatorFactory();
        SessionFactoryImplementor factory = (SessionFactoryImplementor) sessionFactory;
        QueryTranslator translator = translatorFactory.createQueryTranslator(hqlQueryText, hqlQueryText, Collections.EMPTY_MAP, factory, null);
        translator.compile(Collections.EMPTY_MAP, false);
        return translator.getSQLString();
    }
    return null;
}

and I have this filter in .hbm.xml file of domain class:

<filter name="userAuthorize" condition="some sql query here" />

but I don't know how I should tell hibernate to apply this filter when converting from hql to sql.

Assume that I call above method like this:

public Session getSession() {
    try {
        return sessionFactory.getCurrentSession();
    }
    catch (Exception e) {
    }
    return sessionFactory.openSession();
}

public List<DomainClass> getAll() {
    String hql = " some hql query ";
    Session session = getSession();
    String sql = toSql(hql);

    return session.createSQLQuery(sql).list();
}

Not a great Idea. But maybe It helps.

HQL and SQL have some differences, for instance with join , 'on' is used in SQL and 'with' is used in HQL. So maybe you can use list of words that are unique to HQL and check for them in your String using

hql.contains("with") or hql.indexOf("with").

It is not the responsibility of the QueryTranslator to apply filters. Also, filters don't get applied to native SQL.

It looks like you just want to execute the HQL query? There is no need to have it translated to SQL first:

public List<DomainClass> getAll() {
    String hql = " some hql query ";
    return session.createQuery(hql).list();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM