Problems with JPA request using Timestamp

my problem is a bit like this : I want to get rows whose date is less than 20 minutes from the current time, my original code is:

   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();  

      

My essence:

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

      

when i run this code:

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)

      

error from this line:

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

      

Any help?

+3


source to share


1 answer


It looks like you are comparing c.date, which is a Date (Timestamp) with a String, since you are setting nd in a string query and are surrounded by single quotes. You must use a named parameter and set the nd variable to that parameter.



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

      

+5


source







All Articles