HQL选择使用日期作为条件错误

时间:2011-01-08 22:06:27

标签: sql hibernate date hql

在HQL中,我试图使用日期作为标准获取一些数据,但我收到错误:

代码:

Date DatePlaced=new Date();
        auction.setDatePlaced(DatePlaced);
        auction.setUser((Users) getThreadLocalRequest().getSession(true).getAttribute("User"));
        UpdateDatabase(auction);
        Session session = gileadHibernateUtil.getSessionFactory().openSession();
        Long UserId=(Long) getThreadLocalRequest().getSession(true).getAttribute("UserId");
        String HQL="From Auction auction where User.UserId="+UserId +" and DatePlaced='"+DatePlaced+"'";
        Auction A1=(Auction) session.createQuery(HQL).list().get(0);


Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    at java.util.ArrayList.get(ArrayList.java:322)
    at com.BiddingSystem.server.ServiceImpl.UpdateAuction(ServiceImpl.java:543)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at net.sf.gilead.gwt.PersistentRemoteService.processCall(PersistentRemoteService.java:174)

这里发生的事情主要是由于日期,但因为没有找到数据因为日期不匹配但是用于搜索的数据与我在上面设置的数据相同,所以应该返回1行

1 个答案:

答案 0 :(得分:3)

尝试使用命名参数,而不是尝试从字符串构建查询

Auction A1=(Auction) session
           .createQuery("From Auction auction where User.UserId=:userId and DatePlaced=:placed")
           .setLong("userId",userId)
           .setDate("placed",placed)
           .list().get(0);