Rewrite Hibernate Criteria with IN clause so can reuse same PreparedStatement with different number of IN clauses
05:54 26 Jun 2019

I use the following Hibernate query a lot when retrieving multiple records by their primary key

       Criteria c = session
                .createCriteria(Song.class)
                .setLockMode(LockMode.NONE)
                .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
                .add(Restrictions.in("recNo", ids));
        List songs = c.list();

The problem is the number of ids can vary from 1 - 50, and every different number of ids requires a different PreparedStatement. That, combined with the fact that any particular prepared statement is tied to a particular database pool connection means that the opportunity to reuse a PreparedStatement is quite low.

Is there way I can rewrite this so that the same statement can be used with different number of in values? I think I read somewhere it could be done by using ANY instead but cannot find the reference.

sql hibernate hibernate-criteria