我有一个hql来显示基于between(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);


任何帮助将是荣幸:)

最佳答案

您无需引用参数。即:

您应该写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);

关于java - 找不到命名参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20464636/

10-10 15:10