2012-04-06 155 views
3
JPA查詢

我的問題有點類似於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+"'") 

任何幫助嗎?

回答

5

看起來您正在比較日期(Timestamp)和字符串c.date,因爲您正在設置字符串查詢中的nd,並且被單引號包圍。您應該使用命名參數,並將nd變量設置爲該參數。

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

感謝它的工作! – 2012-04-06 16:39:45