9
votes

I have a requirement to fetch selected rows from Oracle database based on ids supplied as an array, something like the SELECT ... FROM table_name WHERE id IN() query.

In my attempts to do so, I'm trying to use the org.hibernate.setParameterList(String name, Object[] values) method in my DAO as follows.

@Service
@Transactional(readOnly = true, propagation=Propagation.REQUIRES_NEW)
public final class ProductImageDAO implements ProductImageService {

    @SuppressWarnings("unchecked")
    public List<Object[]> getFileName(String[] list) {
        return sessionFactory
                .getCurrentSession()
                .createQuery("SELECT prodImageId, prodImage FROM ProductImage WHERE prodImageId=:list")
                .setParameterList("list", list).list();
    }
}

The parameter of type String[] in the given method is supplied from the respective Spring controller class.

It causes the following exception to be thrown.

org.hibernate.hql.ast.QuerySyntaxException: unexpected token: , near line 1, column 78 [select prodImageId, prodImage from model.ProductImage where prodImageId=:id0_, :id1_, :id2_, :id3_, :id4_, :id5_]

What is the way to retrieve the selected rows based on list of ids using Hibernate?

2

2 Answers

22
votes
String queryString = "select acc from cgix.trust.domain.PtbnAccount as acc where acc.accountId IN (:accountdIds)";
Query query = session.createQuery (queryString);
query.setParameterList("accountIds", accountFilter);

Assuming accountFilter is a List object. Keep in mind that you should not pass empty lists since that would result in the following SQL (which won't work): ... WHERE xyz IN () ... (note the empty in-clause).

5
votes

The problem that most people make here is that they still want to use,

query.setParameter("accountIds", accountFilter);

instead of

query.setParameterList("accountIds", accountFilter);

use setParameterList() when dealing with lists