Reputation: 28294
I have an Entity that has a NameQuery
like this:
@Entity
@Table(name = "ping")
@NamedQueries({
@NamedQuery(name = "Ping.getPingsOlderThan", query = "SELECT p FROM Ping p WHERE p.pingTime > :time")
})
public class Ping extends BaseModel implements Serializable{
...
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "ping_time")
private Date pingTime;
And I call that NamedQuery
form this code:
public List<Ping> getPingsOlderThan(Integer seconds) {
Calendar now = Calendar.getInstance();
//make sure seconds is negative, so it subtracts
seconds = seconds > 0 ? seconds * -1 : seconds;
now.add(Calendar.SECOND, seconds);
Date time = now.getTime();
try{
Query query = getEntityManager().createNamedQuery("Ping.getPingsOlderThan");
query.setParameter("time", time);
return query.getResultList();
}
catch(Exception e){
logger.log(Level.SEVERE, "Could not get pings",e);
return null;
}
}
Basically it gets all Pings
that are older than the the seconds pass in (at least thats what it is supposed to do). So if 30 is passed in, it should get all Pings
in the last 30 seconds. What I get are all Pings
in the database. Even those older than than the value I pass in.
Is there something wrong with my query? Does it have anything to do with the fact that I use a java.util.Date
?
Upvotes: 0
Views: 3259
Reputation: 28294
I figured it out. I had to pass in the TemporalType
to the query paramater. Otherwise, it was using the Date
version which didnt have seconds.
query.setParameter("time", time,TemporalType.TIMESTAMP);
Upvotes: 1