使用可选参数在 HQL 中动态搜索查询?

Ahm*_*mad 3 java hibernate hql dynamicquery

我正在开发一个需要搜索功能的应用程序,我想编写根据参数动态创建的 HQL 查询。目前我有 4 个参数,而搜索所有参数都是必需的,或者根据用户想要搜索的方式需要 1 或 2 或 3 个参数。

public List<Plot> fetchSearchedPlots(int plotType, String plotSize, String min, String max)
    {
        Session session = sessionFactory.getCurrentSession();
        List<Plot> searchedLists = new ArrayList<Plot>();
        String query = "FROM Plot where type = ? and size = ? and price >= ? and price <= ?";
        searchedLists = (List<Plot>)session.createQuery( query )
                .setInteger( 0, plotType )
                .setString( 1, plotSize )
                .setString( 2, min )
                .setString( 3, max ).list();
        return searchedLists;
    }
Run Code Online (Sandbox Code Playgroud)

这是我对所有 4 个参数的一般查询,现在我必须编写一个使用多个可选参数的搜索查询,如何使用可选参数进行此查询?请将我的查询转换为动态可选参数查询?谢谢

Ahm*_*mad 7

我自己像这样转换了查询

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;
Run Code Online (Sandbox Code Playgroud)