大家好我试图在jpa中进行范围查询,我可以在设定范围内搜索DOB
我让用户在calander上输入详细信息,然后将其传递给此代码
public List<User> dobRangeSearch(Date dateOfBirthSearch1, Date dateOfBirthSearch2) {
Query q = em.createQuery("SELECT u FROM USERS U WHERE u.DATEOFBIRTH BETWEEN "+ dateOfBirthSearch1 + " and " + dateOfBirthSearch2);
return q.getResultList();
}
但是我收到以下错误:
java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Syntax error parsing [SELECT u FROM USERS U WHERE u.DATEOFBIRTH BETWEEN Sun Dec 01 00:00:00 GMT 2013 and Wed Dec 04 00:00:00 GMT 2013].
[28, 95] The expression is not a valid conditional expression.
运行此搜索的正确方法是什么?
谢谢
修改
即使我使用calander和date函数创建了值,但放入数据库的记录格式为
'2013-12-02'
那么如何从输入中删除数据呢?
答案 0 :(得分:1)
您将Date.toString()
输出放在查询中,以便使用DateFormater以正确的格式获取使用参数的日期字符串。
public List<User> dobRangeSearch(Date dateOfBirthSearch1, Date dateOfBirthSearch2) {
Query q = em.createQuery("SELECT u FROM USERS U WHERE u.DATEOFBIRTH BETWEEN :date1 and :date2)
.setParameter("date1", dateOfBirthSearch1)
.setParameter("date2", dateOfBirthSearch2;
return q.getResultList();
}