在HQL中动态搜索带有可选参数的查询? [英] dynamically Search Query in HQL with optional Parameter?
问题描述
我正在开发一个需要搜索功能的应用程序,我想编写根据参数动态创建的HQL查询. 目前,我有4个参数,而搜索所有参数都是必需的,或者根据用户想要搜索的方式需要1或2或3个参数.
i am developing an application in which i need search functionality, i want to write HQL query that dynamically create according to parameters. Currently i have 4 parameters, while searching all parameters are required or 1 or 2 or 3 parameters required according to how user want to searchs.
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;
}
这是我对所有4个参数的常规查询,现在我必须编写一个搜索查询,其中使用多个可选参数,如何使用可选参数进行此查询?请将我的查询转换为动态可选参数查询? 谢谢
this is my general query for all 4 parameters, now i have to write a search query in which i use multiple optional parameters, How to make this query with optional parameters? kindly convert my query to dynamically optional parameters query ? Thanks
推荐答案
我这样自己转换查询
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;
这篇关于在HQL中动态搜索带有可选参数的查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!