有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

命名查询中的java字符串日期生成ClassCastException

我正在尝试为所有字符串化参数创建一个命名查询。这就是我的严格化方法:

    public Collection<Companypermcache> findExpiredPerms() {
        String date = DateUtils.getSQLDate(DateUtils.getToday());
        StringBuffer qbe = new StringBuffer("select cpc from Companypermcache cpc");
        qbe.append(" where cpc.expire < '"+date+"'");
        return super.findByQuery(qbe.toString());
    }

我将其转换为命名查询,如下所示

        String date = DateUtils.getSQLDate(DateUtils.getToday());
        StringBuffer qbe = new StringBuffer("select cpc from Companypermcache cpc");
        qbe.append(" where cpc.expire < :date");
        return super.findByQuery(qbe.toString(),"date",date);
    }

但这会产生

java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date at org.hibernate.type.descriptor.java.JdbcTimestampTypeDescriptor.unwrap(JdbcTimestampTypeDescriptor.java:24) at org.hibernate.type.descriptor.sql.TimestampTypeDescriptor$1.doBind(TimestampTypeDescriptor.java:48) at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:74) at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:253) at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:248) at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:52) at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:627) ...

例外

但是,如果我像下面这样更新命名查询,我没有任何异常,一切看起来都很好

        String date = DateUtils.getSQLDate(DateUtils.getToday());
        DateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date edate = simpleDateFormat.parse(date);
        StringBuffer qbe = new StringBuffer("select cpc from Companypermcache cpc");
        qbe.append(" where cpc.expire < :date");
        return super.findByQuery(qbe.toString(),"date",edate);
    }

然而,我真的不理解这种差异以及解析的必要性。我在我的项目中有很多地方使用getSQLDate(),所以我担心是否要解析所有这些日期? 除此之外,我的表中的edate类型是DATETIME

当我们将日期作为参数传递给命名查询时,为什么需要解析日期


共 (0) 个答案