[英]how to include a greater than Date in a JPA query?
I have a JPA based project like so: 我有一个基于JPA的项目,如下所示:
@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: 在我的DAO中,我这样做:
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: 当我运行DAO代码时,出现此错误:
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. 您只能将值作为参数传递,因此应将e.data LIKE '%?1%'
替换为e.data LIKE ?1
,并在Java代码中用%
e.data LIKE ?1
文本。
I think it's somehow related to the fact that you cannot use parameters inside literals (ie '%?1%'
). 我认为这与不能在文字中使用参数(即'%?1%'
)有关。
Try the following query instead: 请尝试以下查询:
SELECT e FROM Event e WHERE e.data LIKE CONCAT('%', ?1, '%') AND e.eventDate > ?2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.