我已经重写了这个问题,以便说清楚。
我有一个这样的实体:
@Entity
@NamedQueries({
@NamedQuery(
name = "myObj.findCurrentUsingFunction",
query = "from MyObj where insertDate = current_date() "),
@NamedQuery(
name = "myObj.findCurrentUsingParameter",
query = "from MyObj where insertDate = :currentDate")
})
public class MyObj {
@Id @GeneratedValue @Column
private Long id;
@Column @Temporal(TemporalType.DATE)
private Date insertDate;
/* getter, setter */
}
我的测试失败了:
@Test
public void findCurrentUsingFunction() throws Exception {
final MyObj myObj = new MyObj();
myObj.setInsertDate(new Date());
final Session session = dao.getSessionFactory().getCurrentSession();
session.saveOrUpdate(myObj);
final Query namedQuery =
session.getNamedQuery("myObj.findCurrentUsingFunction");
final List results = namedQuery.list();
Assert.assertEquals("size",1L, (long) results.size());
}
Hibernate:从双Hibernate中选择hibernate_sequence.nextval: 插入MyObj(insertDate,id)值(?,?)Hibernate:select myobj0_.id为来自MyObj的id0_,myobj0_.insertDate为insertDate0_ myobj0_ where myobj0_.insertDate = current_date
java.lang.AssertionError:期望的大小:< 1>但是:< 0>
和通过测试
@Test
public void findCurrentUsingParameter() throws Exception {
final MyObj myObj = new MyObj();
myObj.setInsertDate(new Date());
final Session currentSession = dao.getSessionFactory().getCurrentSession();
currentSession.saveOrUpdate(myObj);
final Query namedQuery =
currentSession.getNamedQuery("myObj.findCurrentUsingParameter");
namedQuery.setDate("currentDate", new Date());
final List results = namedQuery.list();
Assert.assertEquals("size",1L, (long) results.size());
}
方言是:
hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
答案 0 :(得分:5)
您在HSQL语句中使用sql函数,因此它不起作用。删除括号以使用hibernate current_date函数,如下所示:
@NamedQuery(
name = "entity.findCurrent",
query = "from EntityName where insertDate = current_date")
或者,我会这样做(实际上我也会使用joda-time来创建我的日期时间变量currentDate)
@NamedQuery(
name = "entity.findCurrent",
query = "from EntityName where insertDate = :currentDate")
然后在调用命名查询时传入日期
session.getNamedQuery(findCurrent).setDate("currentDate", currentDate);
或者您可以使用critiera。