简体   繁体   中英

JPA/Hibernate Query do not recognize named parameters

This method won't work with parameters

    @Override
public List<T> findBy2Params(Class c, String param1, String value1, String param2, String value2) {

    Query q = em.createQuery("select o from :class o where o.:param1 =   ':value1' "
            + " and o.:param2 = 'value2' ");
    q.setParameter("class", c.getName());
    q.setParameter("param1", param1);
    q.setParameter("value1", value1);
    q.setParameter("param2", param2);
    q.setParameter("value2", value2);
    return q.getResultList();
}

throws an error on the ":" ;does not treat it as a parameter

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: : near line 1, column 15 [select o from :class o where o.:param1 = ':value1' and o.:param2 = 'value2' ]

Your query will not work because you can't bind table or column names like that.

The table name and columns related need to be known when the execution plan comes to play, it happens before the parameter binding.

The only way of doing this is replacing these values before passing to the HQL, or using a more dynamic approach to build the query at runtime using the Criteria API for example.

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