gpt4 book ai didi

java - EclipseLink jpql "where clause"比较时间戳未按预期工作

转载 作者:行者123 更新时间:2023-12-01 06:09:23 25 4
gpt4 key购买 nike

我选择使用时间戳列的 jpql“where 子句”没有按预期“过滤”。

它似乎对时间戳的“日期”部分敏感,但是忽略了“时间”部分。

table1.tmstmp 列定义为:“TMSTMP TIMESTAMP NOT NULL”

table1 实体包含以下命名查询:

@NamedQuery(name = "table1.getUpdTime", query = "SELECT e FROM table1 e     
WHERE e.tmstmp >= :tmstmp order by e.tmstmp asc")

tmstmp 属性定义如下:

@Column(name = "TMSTMP", nullable = false)
private Timestamp tmstmp;

它的用法如下:

TypedQuery<EsEvnt> query = em.createNamedQuery("table1.getUpdTime",
table1.class).setParameter("tmstmp", tmstmp);

例如,当上面的时间戳变量(“tmstmp”)等于“2016-06-30T09:28:33.247-04:00”时,它将返回日期部分为:2016-06 的所有记录-30。

有什么想法吗?

我想依靠“where 子句”来使用整个时间戳来显式选择。

更新

我使用“CAST”函数修改了我的查询(似乎需要 native 查询),如下所示,并且它似乎一致工作:

//...note, date is in ISO format...
LocalDateTime ldt = LocalDateTime.parse(tmstmpString, DateTimeFormatter.ISO_DATE_TIME);
Timestamp tmstmp = Timestamp.valueOf(ldt);
-
-
-
// (see "native query", coded below)...
Query query = em.createNativeQuery("SELECT * FROM table1 e WHERE e.tmstmp >= CAST(?1 as TIMESTAMP)", Table1.class)
.setParameter(1, tmstmp);
List<Table1> resultList = query.getResultList();
<小时/>

WebLogic 12.1.3

DB2

Java 8

EclipseLink 2.1

最佳答案

下面是对我有用的...

假设...

    //...note, date is in ISO format...
LocalDateTime ldt = LocalDateTime.parse(tmstmpString, DateTimeFormatter.ISO_DATE_TIME);
Timestamp tmstmp = Timestamp.valueOf(ldt);

这是一种方法...

    Query query = entityManager.createNativeQuery("SELECT * FROM table1 e WHERE e.tmstmp >= CAST(?1 as TIMESTAMP)", Table1.class)  
.setParameter(1, tmstmp);
List<Table1> resultList = query.getResultList();

还有另一种方法...

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Table1> criteriaQuery = criteriaBuilder.createQuery(Table1.class);
Root<Table1> table1 = criteriaQuery.from(Table1.class);

Expression<Byte> expression = table1.get("tmstmp"); // ...NOTE: column name is "tmstmp"...
Expression<Timestamp> castFunction = criteriaBuilder.function("TIMESTAMP", Timestamp.class, expression);
Predicate predicate = criteriaBuilder.greaterThanOrEqualTo(castFunction, tmstmp);

//NOTE: should be able to add to predicate...
// e.g.,
// predicate = criteriaBuilder.and(predicate, otherPredicate);

criteriaQuery.where(predicate);
TypedQuery<Table1> query = entityManager.createQuery(criteriaQuery);
List<Table1> resultList = query.getResultList();

关于java - EclipseLink jpql "where clause"比较时间戳未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38126243/

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