无法找到命名参数

时间:2013-12-09 06:40:43

标签: java hibernate hql

我有一个hql来显示基于(to_date)之间的数据,但我得到Could not locate named parameter错误

这是我的代码

    SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
    Date date1 = Calendar.getInstance().getTime();
    String tgl1 = sdf1.format(date1);
    String Tanggal_awal = tgl1+" 00:00:00";
    System.out.println(Tanggal_awal);

    SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");
    Date date2 = Calendar.getInstance().getTime();
    String tgl2 = sdf2.format(date2);
    String Tanggal_akhir = tgl2+" 23:59:59";
    System.out.println(Tanggal_akhir);

    Query LoadSource = session_source.createQuery("select CLIENT,SERVICE,SERVICE_TYPE,PROVIDER_CODE,COUNT(*) FROM SwitcherServiceSource" +
            " where TIMESTAMP between to_date(':awal','dd-MM-yyyy HH24:MI:SS') and to_date(':akhir','dd-MM-yyyy HH24:MI:SS')" +
            " and PROVIDER_CODE is not null group by CLIENT,SERVICE,SERVICE_TYPE,PROVIDER_CODE order by CLIENT,SERVICE,SERVICE_TYPE,PROVIDER_CODE");
    LoadSource.setParameter("awal", Tanggal_awal);
    LoadSource.setParameter("akhir", Tanggal_akhir);

任何帮助都会很愉快:)

1 个答案:

答案 0 :(得分:1)

您无需引用参数。即:

您应该写where TIMESTAMP between to_date(':awal','dd-MM-yyyy HH24:MI:SS') and to_date(':akhir','dd-MM-yyyy HH24:MI:SS')

而不是where TIMESTAMP between to_date(:awal,'dd-MM-yyyy HH24:MI:SS') and to_date(:akhir,'dd-MM-yyyy HH24:MI:SS')

更好的是,您可以(并且您应该)甚至避免将字符串绑定到该参数。您可以绑定日期/时间戳,以便查询更有效和可读:where TIMESTAMP between :awal and :akhir,并在您的代码中执行类似的操作:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

Date fromDate = cal.getTime();

cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);

Date toDate = cal.getTime();

Query loadSource = session_source.createQuery("select blablabla FROM SwitcherServiceSource" +
        " where TIMESTAMP between :awal and :akhir " +
        " and blablabla group by blabla order by blablabla");
loadSource.setParameter("awal", fromDate );
loadSource.setParameter("akhir", toDate);