简体   繁体   English

如何比较 JPQL 查询中的 LocalDateTime 值?

[英]How to compare LocalDateTime values in JPQL query?

It is necessary to select dataset using JPQL query with optional condition - comparing the field value ( LocalDateTime type) with a user-specified parameter (also LocalDateTime type). select 数据集需要使用带有可选条件的 JPQL 查询 - 将字段值( LocalDateTime类型)与用户指定的参数(也是 LocalDateTime 类型)进行比较。

First I made a well working code:首先,我制作了一个运行良好的代码:

return entityManager.createQuery(
    "SELECT new com.******.*******.*******.****.models.dto.SomeDto " +
    "(s.id, " +
    "s.userId) " +
    "s.persistDate) " +
    "FROM Some s WHERE s.userId = :userId 
    AND s.persistDate >= :userDateTime", SomeDTO.class)
    .setParameter("userId", userId)
    .setParameter("userDateTime", userDateTime)

This code works but there is one problem: this condition may exist or may not exist - dependent on app logic.这段代码有效,但存在一个问题:这种情况可能存在也可能不存在——取决于应用程序逻辑。 Therefore, there is a need not to use injection using.setParameter (for this condition), but to form a string (which may be empty) depending on the logic and then add to the request:所以需要不使用注入using.setParameter(针对这种情况),而是根据逻辑组成一个字符串(可能为空),然后添加到请求中:

String extraCondition = (userDateString.equals("false")) ? "" : 
    "AND s.persistDateTime >= " + userDateString;
return entityManager.createQuery(
    "SELECT new com.******.*******.*******.****.models.dto.SomeDto " +
    "(s.id, " +
    "s.userId) " +
    "s.persistDate) " +
    "FROM Some s WHERE s.userId = :userId " + extraCondition, SomeDTO.class)
    .setParameter("userId", userId)

But the problem is that no matter how I tried to format the userDateString variable, I get an Internal Server Error.I even tried using just a text string instead of variable (tried with different formatting):但问题是,无论我如何尝试格式化 userDateString 变量,我都会收到内部服务器错误。我什至尝试只使用文本字符串而不是变量(尝试使用不同的格式):

String extraCondition = (userDateString.equals("false")) ? "" : 
    "AND s.persistDateTime >= 2023-01-27T23:30:50";

But the result is also bad - Internal Server Error.但结果也很糟糕——Internal Server Error。

I also tried using the.isAfter method instead of the ">=" operator, but that didn't help either.我还尝试使用 .isAfter 方法代替“>=”运算符,但这也无济于事。

How to inject LocalDateTime values comparing into query as String?如何将比较的LocalDateTime值作为字符串注入查询?

even if the date string may or may not be necesssary, you can (and should,) still use parameter injection.即使日期字符串可能是也可能不是必需的,您仍然可以(并且应该)使用参数注入。 not formatted values.没有格式化的值。

Basically, your code should look like this:基本上,您的代码应如下所示:

String queryStr = ....;
if(someCondition) {
  queryStr += " AND s.persistDate >= :userDateTime";
}
Query q = em.createQuery(queryStr).setParameter("userId", userId);
if(someCondition) {
  q.setParameter("userDateTime", userDateTime);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM