This blog is mainly about Java...

Tuesday, January 11, 2011

Remember that ordinal parameters are 1-based in hibernate

I got this strange exception java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based!

When running this query in hibernate/jpa

jbpmContext.getSession().createQuery("select pi from org.jbpm.graph.exe.ProcessInstance pi where pi.id = ?1 or pi.id = ?2 or pi.id =?3")
            .setParameter(1, 9L).setParameter(2, 10L).setParameter(3, 11L).list();


Which is very strange. The reason why hibernate cannot figure this out is because the ejb 3 form
("?1")
is interpreted as a named parameter! So here we actually have to write it as
.setParameter("1", 9L)
instead, or change the query and only type ? like so.

jbpmContext.getSession().createQuery("select
 pi from org.jbpm.graph.exe.ProcessInstance pi where pi.id = ? or pi.id
 = ? or pi.id =?").setParameter(0, 9L).setParameter(1, 10L).setParameter(2, 11L).list();


The message about "1-based" is misleading here. It refers to the fact the the metadata for parameters is actually indexed by their sql positions (which is 1-based).

Good to know!

No comments:

Labels