gpt4 book ai didi

java - 使用 JPA 2.1 对日期字段使用 Like 表达式

转载 作者:行者123 更新时间:2023-11-29 04:39:32 26 4
gpt4 key购买 nike

我正在尝试使用命名查询在日期字段上执行带有 LIKE 表达式的查询,如下所示;

public Users getResultsByDate(Date regDate){
List<Users> dbUsers = new ArrayList<Users>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Query searchQuery = getEntityManager().createNamedQuery("getUserByRegDate");
searchQuery.setParameter("regDate", "%"+dateFormat.format(regDate)+"%");
try{
dbUsers = searchQuery.getResultList();
}
catch(Exception ex){
dbUsers = new ArrayList<Users>();
}
return dbUsers;

对应类中的名称查询为;

 @NamedQuery(name = "getUserByRegDate", query = "SELECT user FROM Users user WHERE user.regDate LIKE :regDate"),

查询使用以前的 JPA 2.0 版本工作。当我在 JPA 2.1 上运行时执行相同的操作时出现以下错误;

You have attempted to set a value of type class java.lang.String for parameter :regDate with expected type of class java.util.Date ...

在 JPA 2.1 上运行时如何解决这个问题?它在 JPA 2.0 中工作正常。

最佳答案

JPA 规范 4.6.10

The syntax for the use of the comparison operator [NOT] LIKE in a conditional expression is as follows:

like_expression ::=
string_expression [NOT] LIKE pattern_value [ESCAPE escape_character]

The string_expression must have a string value. The pattern_value is a string literal or a string-valued input parameter ...

所以不,它在 JPA 2.0 中“工作”;在 LIKE 表达式中使用日期不是任何 JPA 规范的一部分。它可能只是偶然工作,因为一些 JPA 提供者(哪个?)没有进行检查并执行 JPA 规范......

关于java - 使用 JPA 2.1 对日期字段使用 Like 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39793432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com