gpt4 book ai didi

java - Java JPA 中按日期查询

转载 作者:行者123 更新时间:2023-11-29 23:19:55 28 4
gpt4 key购买 nike

如何在JPA中查询MySQL中的DateTime?前面的变量是一个以毫秒为单位的 Date() 对象。我会做类似以下的事情:

@Override
@Transactional(readOnly = true)
public List<Entry> findAllBefore(Long before, Integer nEntries)
{

CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
CriteriaQuery<Entry> criteriaQuery = builder.createQuery(Entry.class);

Root root = criteriaQuery.from(Entry.class);
criteriaQuery.select( root );

// seems not to work
criteriaQuery.where( builder.lessThan( root.get( "start" ) , before ) );

TypedQuery<Entry> typedQuery = this.getEntityManager()
.createQuery(criteriaQuery)
.setMaxResults(nEntries)

return typedQuery.getResultList();
}

我希望获得相应表中的所有条目,其中日期时间列“start”位于变量“before”中的值之前。

最佳答案

你能使用谓词吗?也许我的回复中会有编译错误,因为我现在不在我的电脑上,但有了这个,应该很容易找到你的方法。首先在方法签名中,我将传递一个日期(或者可能在方法内将 long 转换为日期)。

约会后:

    CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
CriteriaQuery<Entry> criteriaQuery = builder.createQuery(Entry.class);
List<Predicate> predicates = new ArrayList<Predicate>();
ParameterExpression<Date> param = builder.parameter(Date.class, "start");
predicates.add(builder.lessThanOrEqualTo(root.get("beforeDate"), param)); criteriaQuery.select(customer)
.where(predicates.toArray(new Predicate[]{}));
"EntityManagerVariableName".createQuery(cq).getResultList();

关于java - Java JPA 中按日期查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27416065/

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