gpt4 book ai didi

java - 使用时间戳的 JPA 查询问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:54:06 29 4
gpt4 key购买 nike

我的问题有点类似于this :我想检索日期与当前日期时间相比不超过 20 分钟的行,我的源代码:

   EntityManagerFactory emf=Persistence.createEntityManagerFactory("JavaApplication21PU");
CoordonneesJpaController cjc=new CoordonneesJpaController(emf);
Timestamp nd=new Timestamp(System.currentTimeMillis());//now
nd.setMinutes(nd.getMinutes()-20);

EntityManager em = getEntityManager();
Query qr= em.createQuery("SELECT c FROM Coordonnees c WHERE c.date > '"+nd+"'");
java.util.List<Coordonnees> lC=qr.getResultList();

我的实体:

    public class Coordonnees implements Serializable {
//some code...
@Basic(optional = false)
@Column(name = "DATE", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date date;

当我运行这段代码时:

Exception in thread "main" Local Exception Stack: 
Exception [EclipseLink-3002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.ConversionException
Exception Description: The object [%2012-04-06 16:19:49.179%], of class [class java.lang.String], from mapping [org.eclipse.persistence.mappings.DirectToFieldMapping[date-->APIGPS.PUBLIC.COORDONNEES.DATE]] with descriptor [RelationalDescriptor(javaapplication21.Coordonnees --> [DatabaseTable(APIGPS.PUBLIC.COORDONNEES)])], could not be converted to [class java.sql.Timestamp].
at org.eclipse.persistence.exceptions.ConversionException.incorrectTimestampFormat(ConversionException.java:119)
at org.eclipse.persistence.internal.helper.Helper.timestampFromString(Helper.java:1888)
at org.eclipse.persistence.internal.helper.ConversionManager.convertObjectToTimestamp(ConversionManager.java:726)
at org.eclipse.persistence.internal.helper.ConversionManager.convertObject(ConversionManager.java:107)

错误来自这一行:

   Query qr= em.createQuery("SELECT c FROM Coordonnees c WHERE c.date > '"+nd+"'")

有什么帮助吗?

最佳答案

看起来您正在比较 c.date,它是一个日期(时间戳)和一个字符串,因为您在字符串查询中设置了 nd,并用单引号括起来。您应该使用命名参数,并将 nd 变量设置到该参数中。

Query qr= em.createQuery("SELECT c FROM Coordonnees c WHERE c.date > :nd");
qr.setParameter("nd", nd);

关于java - 使用时间戳的 JPA 查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10045896/

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