@Embeddable
public class Birthday {
private LocalDate value;
// Constructors, getters and setters
}
实体:
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Birthday birthday;
// Constructors, getters and setters
}
除以3的查询:
List<Person> sortedPersons = query.selectFrom(person)
.orderBy(person.birthday.value.month().divide(3).ceil().asc())
.fetch();
使用模板查询:
List<Person> sortedPersons = query.selectFrom(person)
.orderBy(Expressions.dateTemplate(Integer.class, "QUARTER({0})", person.birthday.value).asc())
.fetch();
错误代码:
Caused by: org.eclipse.persistence.exceptions.JPQLException:
Exception Description: Syntax error parsing [select
from Person person
order by ceil(extract(month from person.birthday.value) / 3) asc].
[3165, 3254] The order by item is not a valid expression.
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildException(HermesParser.java:157) ~[com.ibm.websphere.appserver.thirdparty.eclipselink.2.7_1.0.76.jar:?]
at [internal classes]
at com.querydsl.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:101) ~[querydsl-jpa-4.2.2.HL-20230109.202119-8.jar:?]
at com.querydsl.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:94) ~[querydsl-jpa-4.2.2.HL-20230109.202119-8.jar:?]
at com.querydsl.jpa.impl.AbstractJPAQuery.fetch(AbstractJPAQuery.java:201) ~[querydsl-jpa-4.2.2.HL-20230109.202119-8.jar:?]
生日字段在数据库中存储为DATE
问题是,如果我删除方法.ceil()
,那么一切都很好,但四舍五入对我来说很重要,而不是四舍五入我的查询返回不正确的数据(我需要按季度排序)。我尝试使用模板为这一个,但我没有帮助。
如果我不使用.ceil
,我有这样的顺序的数据。
- 2023年11月1日
- 2019 - 03 - 23 00:00:00
- 2019年10月29日星期一
- 2019 - 03 - 23 01:00:00
- 2019 - 03 - 23 00:00:00
- 2019 - 08 - 18 00:00:00
2条答案
按热度按时间tv6aics11#
我现在看到问题了,我用纯Java做了一个演示,使用 * 你的 * 日期。这是因为
java.time.Month
* 不是 * 零索引。运行以下程序,并注意校正(减法,而不是四舍五入)使结果符合预期:ccrfmcuu2#
已更改SQL模板。事实证明,您需要在模板本身中取出一个变量:)