我的问题与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+"'")
有帮助吗?
答案 0 :(得分:5)
看起来你正在比较一个日期(时间戳)的c.date和一个字符串,因为你在字符串查询中设置了nd,并用单引号括起来。您应该使用命名参数,并将nd变量设置为该参数。
Query qr= em.createQuery("SELECT c FROM Coordonnees c WHERE c.date > :nd");
qr.setParameter("nd", nd);