【问题标题】:nested exception is java.lang.IllegalArgumentException: Parameter value [2020-04-20] did not match expected type [java.util.Date (n/a)]]嵌套异常是 java.lang.IllegalArgumentException:参数值 [2020-04-20] 与预期类型不匹配 [java.util.Date (n/a)]]
【发布时间】:2020-08-11 00:44:40
【问题描述】:

我想发送这个请求 http://localhost:8080/{url}?start=2020-04-20&end=2020-04-24&status=success&status=failed

在事务模型中

private java.sql.Timestamp addedOn;

我正在尝试为以下博客的多个过滤器创建动态查询: https://attacomsian.com/blog/spring-data-jpa-specifications

Specs.java 文件 toPredicate 方法

if (criteria.getOperation().equals(SearchOperation.GREATER_THAN)) {
                predicates.add(builder.greaterThan(
                        root.get(criteria.getKey()), criteria.getValue().toString()));
} else if (criteria.getOperation().equals(SearchOperation.LESS_THAN)) {
                predicates.add(builder.lessThan(
                        root.get(criteria.getKey()), criteria.getValue().toString()));
}

这是我的控制器代码

Timestamp start = new Timestamp(dateFormat.parse(request.getParameter("start")).getTime());
Timestamp end = new Timestamp(dateFormat.parse(request.getParameter("end")).getTime());
Specs txnSpecs = new Specs();
txnSpecs.add(new SearchCriteria("addedon", start, SearchOperation.GREATER_THAN_EQUAL));
txnSpecs.add(new SearchCriteria("addedon", end, SearchOperation.LESS_THAN_EQUAL));
txnSpecs.add(new SearchCriteria("status", Arrays.asList(request_params.get("status")), SearchOperation.IN));
List<Transaction> txnList = transactionRepository.findAll(txnSpecs);
return txnList;        

但是当我提出请求时,我得到:

nested exception is java.lang.IllegalArgumentException: Parameter value [2020-04-20] did not match expected type [java.util.Date (n/a)]]

在将 Date 值作为 SQL 查询的参数发送之前,是否需要转换它?或者我需要使用其他类型的日期?

【问题讨论】:

  • 可以加你Transaction实体

标签: java hibernate spring-data-jpa hibernate-criteria


【解决方案1】:

检查您的 dateFormat 是否与您的值模式正确:yyyy-MM-dd :

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

【讨论】:

  • 是的,我的日期格式是正确的。但仍然会出现错误
【解决方案2】:

在将 Date 值作为 SQL 查询的参数发送之前,是否需要转换它?

不,相反,您必须将其保留为 Date,但您可以通过调用 criteria.getValue().toString() 将其转换为字符串。

【讨论】:

  • 当我不使用 toString() 方法时。显示错误:无法解析方法 'greaterThanOrEqualTo(javax.persistance.criteria.Path, java.lang.Object)'
  • 我猜你需要将criteria.getValue() 转换为Date 以满足编译器的要求。
猜你喜欢
  • 1970-01-01
  • 2020-02-23
  • 2019-07-23
  • 2022-11-10
  • 2020-06-22
  • 2019-09-03
  • 2019-10-22
  • 1970-01-01
  • 2022-06-29
相关资源
最近更新 更多