dynamically Search Query in HQL with optional Parameter?

自古美人都是妖i 提交于 2019-12-04 14:02:02

Another variant for dynamic queries is to use Criteria API:

Criteria crit = session.createCriteria(Plot.class);
if (status != null) {
      crit.add(Restrictions.eq("status", status));
}
// other where clauses

For your variant from the question with dynamic criteria creation based on input:

Criteria criteria = session.createCriteria(Plot.class);;
    if(type != null) {
        criteria.add(Restrictions.eq("type", type));
    }
    if(size != null) {
        criteria.add(Restrictions.eq("size", size));
    }
    if(min != null && max != null) {
        criteria.add(Restrictions.between("price", min, max));
    }
    List<Case> searchedLists  = criteria.list();
    return searchedLists;

I Converted query by myself like this

Session session = sessionFactory.getCurrentSession();
        List<Plot> searchedLists = new ArrayList<Plot>();
        Map<String, Object> params = new HashMap<String,Object>();
        String hqlQuery = "from Plot where societyBlock.societyBlockId = :societyBlock";
        params.put( "societyBlock", societyId );
        if(plotType != null)
        {
            hqlQuery += " and type.typeId = :type";
            params.put( "type", plotType );
        }
        if(!plotSize.isEmpty() && plotSize != null && !plotSize.equals( "" ))
        {
            hqlQuery += " and size = :size";
            params.put( "size", plotSize );
        }
        if(min != null)
        {
            hqlQuery += " and price >= :pricemin";
            params.put( "pricemin", min );
        }
        if(max != null)
        {
            hqlQuery += " and price <= :pricemax";
            params.put( "pricemax", max );
        }
        Query query = session.createQuery( hqlQuery );

        for (String str : query.getNamedParameters())
        {
            query.setParameter( str, params.get( str ) );
        }
        searchedLists = (List<Plot>) query.list();
        System.out.println( searchedLists.size() );
        return searchedLists;

You can do something like shown below:

    Map<String, Object> parameters= new HashMap<String,Object>();
    parameters.put("status", status);

    StringBuilder hql = "SELECT employee FROM Employee as employee where 1 = 1";
    if (status != null) {
      hql.append(" and employee.status in :status");
    }


    Query query = session.createQuery(hql.toString());


    for (String p : query.getNamedParameters()) {
      query.setParameter(p, parameters.get(p));
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!