Hibernate查询setParameter无法正常工作

时间:2015-05-26 15:00:45

标签: hibernate

我有以下查询

select count(lead.leadId) as cnt from IRLead lead,IRUser usr,IRLeadWorkflowDtls ld,IRLeadWorkflowState ls where usr.userId = lead.userId and ld.leadId = lead.leadId and ls.id=ld.actionId and ld.currentlyActive=lead.active and lead.orgId= :orgId and lead.active = true and ( lead.firstName LIKE :searchText or lead.email LIKE :searchText or lead.lastName LIKE :searchText or lead.mobile LIKE :searchText or lead.phone LIKE :searchText )  order by lead.firstName asc"

然后我使用以下代码来设置参数,

    Query q = session.createQuery(query.toString());
    q = q.setParameter("orgId", orgId);

     //this loop to check named parameters
    for(String paraName:q.getNamedParameters())
    {
        System.err.println("ParaName "+ paraName);
    }

    for(String name:params.keySet())
    {
        System.err.println(name+" --- "+params.get(name));

        q = q.setParameter(name, params.get(name));
    }

    if (pageNo >= 0)
    {
        q.setFirstResult(pageNo * 10);
        q.setMaxResults(10);
    }
    List<Object[]> objs = q.list();

但我收到以下异常,

     org.hibernate.QueryParameterException: could not locate named parameter [:searchText]
     at org.hibernate.engine.query.ParameterMetadata.getNamedParameterDescriptor(ParameterMetadata.java:101)
at org.hibernate.engine.query.ParameterMetadata.getNamedParameterExpectedType(ParameterMetadata.java:107)

我在这里缺少什么?这让我疯了。

Ayush

2 个答案:

答案 0 :(得分:0)

似乎您在查询中设置了一个名称加上前缀:的参数。

修改此

    q = q.setParameter(name, params.get(name));

到此:

    q = q.setParameter(name.replace(":",""), params.get(name));

这是一个快速/污秽的解决方案。您应该在创建:地图时删除前缀params

答案 1 :(得分:0)

此类问题的原因是-var声明中的 final 查询。 为了使其能够设置参数,请删除-final!