HQL语句使用

1、查询结果是表的部分字段,而不是全部

  • ad是CouponAd 对象
  • coupon 是ad的属性,也是一个实体类

select ad.coupon from CouponAd ad where ad.deleted=false Order by createdDate desc 

2、like模糊搜索

这里变量key是String类型。

        String hql = "from Coupon coupon  where coupon.deleted=false and  coupon.name like :key";
        Map<String, Object> map = new HashMap<>();
        map.put("key", '%' + key + '%');
        List<T> list = list(hql, firstResult, maxResults, map);

3、查询总数

    public int getTotalCountByStore(int storeid) {
        Map<String, Object> map = new HashMap<>();
        map.put("storeid", storeid);
        return getTotalCount(
                "select count(*) from Coupon coupon where coupon.store.id=:storeid",
                map);
    }

 4、条件查询判断某条字段有没有值

from UserCoupon uc where uc.usedDate!=null

5、获取当前日期current_date(),当前时间current_time(),当前时间戳current_timestamp()

6、获取对象的集合属性的size()

 Order by size(coupon.users) desc

7、日期转换成字符串进行比较

where (str(uc.createdDate) like :date0

8、查找最近5天的记录:

calendar.add(Calendar.DATE, -4);
String hql = "from Coupon coupon  where  coupon.startdate>=:date Order by size(coupon.users) desc";
        int firstResult = 15 * (page - 1);
        int maxResults = 15;
        Calendar calendar = Calendar.getInstance();
        //获取最近5天(包括今天)中的第一天的日期
        calendar.add(Calendar.DATE, -4);
        Date date = calendar.getTime();
        Map<String , Object> map=new HashMap<>();
        map.put("date", date);
        List<T> list = list(hql, firstResult, maxResults, map);
        return list;

 注意date类型是可以用>、<来做比较的。

Done

Done!

原文地址:https://www.cnblogs.com/xingyyy/p/3911168.html