How to use the setParameterList() method in Hibernate?

别等时光非礼了梦想. 提交于 2020-01-03 07:40:42

问题


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?


回答1:


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).




回答2:


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



来源:https://stackoverflow.com/questions/14296234/how-to-use-the-setparameterlist-method-in-hibernate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!