条件查询在特定日期和时间之后获取数据

时间:2013-01-17 08:31:08

标签: java sql hibernate jpa hibernate-criteria

我正在使用条件查询如下:我想在我通过的时间和日期之后获取预订。但现在我在相同日期之前通过预订。请帮助..

 @GET
        @Path("/getReservationByUserIdAndTypeAndDateTime/{userid}/{type}/{date}/{time}")
        public List<Reservation> getReservationByAndUserIdAndTypeAndDateTime(@PathParam("userid") int uid, @PathParam("type") int tid,@PathParam("date") Date date,@PathParam("time") Time time) {
            CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Reservation> criteria = builder.createQuery(Reservation.class);
            Root<Reservation> r = criteria.from(Reservation.class);
            TypedQuery<Reservation> query = em.createQuery(
                criteria.select(r).where(new Predicate[]{
                        builder.equal(r.get(Reservation_.usersId), uid), 
                        builder.equal(r.get(Reservation_.reservationsType), tid),

                        builder.greaterThanOrEqualTo(builder.concat(r.get(Reservation_.date), " "+r.get(Reservation_.time)), date.toString()+" "+time.toString())}));
            return query.getResultList();
        }

1 个答案:

答案 0 :(得分:1)

比较格式化为字符串的日期和时间是不可取的,结果可能取决于格式。最好在Date类中使用唯一的Reservation字段:

@Temporal(TIMESTAMP) Date date;

并在查询中使用日期比较:

 builder.greaterThanOrEqualTo(r.get(Reservation_.date), date)

这样time方法中的getReservationByAndUserIdAndTypeAndDateTime参数可以省略,因为date参数会保存日期和时间。