Search code examples
javahibernatecriteria

Hibernate Restrictions.in() only accepts propertyName as String


I have a List of ids:

List<Object> ids;

I need to use this in a criteria query to get all rows with an id that ids contains.

What I have now and works:

    if (ids.size() > 0) {
        for (Object id : ids) {
            preparedResults.add((T)sessionMngr.getSession().
                    createCriteria(rowType).add(Restrictions.idEq(id))
                    .uniqueResult());
        }
    }

So I fetch them one by one, which isn't optimal, but I first tried something like following to get them in one query, but don't know what to put at the ???:

            preparedResults.addAll(sessionMngr.getSession().
                createCriteria(rowType).
                add(Restrictions.in(???, ids)).list());

The first argument of Restrictions.in() is of type String. I can't put a hard coded "id" there as I don't know what the propertyname is. So I don't know how to get the id property as a String there. I saw Projections.id(), but I am not sure if I can use this to get it as a String.


Solution

  • With this solution you can retrieve the name of the id field of your entity. If you use annotations you can have it even shorter as described here. If you don´t use composite primary keys you could also use

    ClassMetadata classMetadata = getSessionFactory().getClassMetadata(myClass); string identifierPropertyName = classMetadata.getIdentifierPropertyName();

    Source of this snippet: here