简体   繁体   中英

how to include a greater than Date in a JPA query?

I have a JPA based project like so:

@Entity
@Table(name="events")
public class Event implements Serializable {
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;
  private String data;
  @Temporal(TemporalType.TIMESTAMP)
  private java.util.Date eventDate;

/* ... getters & setters */
}

In my DAO I do this:

public void checkForEvents(String text, java.util.Date myDate) {

  String query = "SELECT e FROM Event e WHERE e.data LIKE '%?1%' AND e.eventDate > ?2";
  Query q = getEntityManager().createQuery(query);
  q.setParameter(1, text);
  q.setParameter(2, myDate);
  q.getSingleResult() /* and so on ... */

}

When I run the DAO code I get this error:

The parameter "0" is of type "java.lang.String", but the declaration in the query is for type "java.util.Date".

What am I doing wrong?

The message looks strange, but the error is in the first argument. You can only pass values as parameters, so you should replace e.data LIKE '%?1%' by e.data LIKE ?1 , and surround your text with % in the Java code.

I think it's somehow related to the fact that you cannot use parameters inside literals (ie '%?1%' ).

Try the following query instead:

SELECT e FROM Event e WHERE e.data LIKE CONCAT('%', ?1, '%') AND e.eventDate > ?2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM