如果查询是动态语句,如何在hibernate中绑定查询参数?

时间:2016-08-04 06:34:29

标签: java sql-server hibernate

我的动态查询为:

DECLARE @LOERangeMin int =0 ;
       DECLARE @LOERangeMax int = 0;
       DECLARE @CycleStartStatus nvarchar(500) = :param1;
       DECLARE @CycleEndStatus nvarchar(500) = :param2;
       DECLARE @Team nvarchar(100) = NULL;
       DECLARE @ReportStartDate datetime = NULL;
       DECLARE @ReportEndDate datetime = GETDATE();

select min([Cycle Time]) AS AvgMinCycleTime,max([Cycle Time]) AS AvgMaxCycleTime,AVG([Cycle Time]) AS AvgCycleTime
from EpicTable where EpicStartStatusName = @CycleStartStatus  and EpicEndStatusName = @CycleEndStatus
  

我通过将此查询作为字符串传递给:

来准备Query对象
Query que = session.createSQLQuery(queryString);
  

在此我想使用que.setParameter(“param1”,CycleStartStatus)设置CycleStartStatus和CycleEndStatus;和que.setParameter(“param2”,CycleEndStatus);

我试过这种方式,但它显示“org.hibernate.QueryParameterException:找不到命名参数[param1]”。所以有人可以帮助我,我该怎么做?

1 个答案:

答案 0 :(得分:0)

您必须使用以下表示法放置HQL参数::paramName。像这样:

select min([Cycle Time]) AS AvgMinCycleTime,
max([Cycle Time]) AS AvgMaxCycleTime,
AVG([Cycle Time]) AS AvgCycleTime
from EpicTable where EpicStartStatusName = :param1  
and EpicEndStatusName = :param2

然后:

Query que = session.createSQLQuery(queryString);
que.setParameter("param1",CycleStartStatus);
que.setParameter("param2",CycleEndStatus);