如何动态搜索hql中的两个日期? [英] How to dynamically search between two dates in hql?

查看:111
本文介绍了如何动态搜索hql中的两个日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个日期搜索字段,即从和。我必须从用户表中检索记录,这些记录的startDate位于搜索字段中输入和输出的日期之间,如果from和to日期为空,则必须从用户表中检索所有记录。



我试过以下的hql查询:

$ $ $ $ $ $ c $ FROM USER $ b $ WHERE
:start_flag = 1

STARTDATE:from和:to

这里start_flag的类型是int,如果from和to为null,那么它被设置为1。

  query.setParameter(from, startDt); 
query.setParameter(to,endDt);
query.setParameter(start_flag,startFlag);
l = query.list();

这里的数据类型是:

startDt - java.util.Date

endDt- java.util.Date

startFlag-int



当我运行上面的查询时,往返等于null ,我得到以下异常:

SQL错误:932,SQLState:42000
$ b ORA-00932:不一致的数据类型:预计DATE得到BINARY

你能告诉我如何编写HQL查询来实现上面的功能吗?

解决方案

过滤它是这样的:

  String query =FROM USER WHERE:start_flag = 1; 
if(startDt!= null&& endDt!= null){
query + =OR STARTDATE between:start_date and:end_date;
}

TypedQuery< USER> hql = entityManager.createQuery(query);

if(startDt!= null&& endDt!= null){
hql.setParameter(start_date,startDt).setParameter(end_date,endDt);
}
列表< USER> result = hql.setParameter(start_flag,startFlag).list();


I have two Date search field namely from and to. I have to retrieve records from the user table whose startDate lies between the from and to dates entered in the search fields and if the from and to dates are null I have to retrieve all the records from the user table.

I tried the following hql query:

FROM USER 
WHERE 
:start_flag =1 
OR  
STARTDATE between :from and :to

Here start_flag is of type int which is set to 1 if from and to are null.

query.setParameter("from",startDt);
query.setParameter("to",endDt);
query.setParameter("start_flag",startFlag);
l=  query.list();

Here datatypes are:

startDt - java.util.Date

endDt- java.util.Date

startFlag- int

When I run the above query with to and from equal to null I get the following exception:

SQL Error: 932, SQLState: 42000

ORA-00932: inconsistent datatypes: expected DATE got BINARY

Could you tell me how to write the HQL query to achieve the above functionality ?

解决方案

filter it like this:

String query = "FROM USER WHERE :start_flag =1 ";
if(startDt!=null && endDt!=null){
   query +="OR STARTDATE between :start_date and :end_date";
}

TypedQuery<USER> hql = entityManager.createQuery(query);

if(startDt!=null && endDt!=null){
   hql.setParameter("start_date",startDt).setParameter("end_date",endDt);
}
List<USER> result = hql.setParameter("start_flag",startFlag).list();

这篇关于如何动态搜索hql中的两个日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆