如何在Hibernate中编写按日期年、月筛选的查询语句?
没问题,我来帮你把这两个MySQL查询转换成Hibernate支持的查询语句,结合你的实体类映射来实现~
首先明确前提:假设你对应的Java实体类名为YourEntity(记得替换成你实际的类名),字段对应关系如下:
id→ int 类型name→ String 类型date→ Timestamp 类型
1. 查询2018年的数据(对应MySQL:select * from table where year(date)='2018')
方式一:HQL查询
Hibernate的HQL支持直接调用数据库的日期函数,写法和MySQL很接近:
FROM YourEntity WHERE YEAR(date) = 2018
如果需要指定返回字段,也可以写成:
SELECT id, name, date FROM YourEntity WHERE YEAR(date) = 2018
方式二:JPA Criteria查询
如果偏好类型安全的Criteria方式,可以这样写:
// 获取CriteriaBuilder和CriteriaQuery实例 CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<YourEntity> cq = cb.createQuery(YourEntity.class); Root<YourEntity> root = cq.from(YourEntity.class); // 添加查询条件:date字段的年份等于2018 cq.select(root).where( cb.equal(cb.function("year", Integer.class, root.get("date")), 2018) ); // 执行查询获取结果 List<YourEntity> resultList = entityManager.createQuery(cq).getResultList();
2. 查询5月的数据(对应MySQL:select * from table where month(date)='05')
方式一:HQL查询
同样使用MONTH函数,注意这里直接传入整数5即可,不需要带前导零:
FROM YourEntity WHERE MONTH(date) = 5
方式二:JPA Criteria查询
用Criteria实现的话:
CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<YourEntity> cq = cb.createQuery(YourEntity.class); Root<YourEntity> root = cq.from(YourEntity.class); cq.select(root).where( cb.equal(cb.function("month", Integer.class, root.get("date")), 5) ); List<YourEntity> resultList = entityManager.createQuery(cq).getResultList();
额外说明
如果你用的是Hibernate传统的Session API(而非JPA EntityManager),Criteria的写法可以换成:
Session session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(YourEntity.class); criteria.add(Restrictions.eq("date.month", 5)); // 年份查询同理:Restrictions.eq("date.year", 2018) List<YourEntity> resultList = criteria.list();
不过更推荐使用JPA标准的CriteriaBuilder,兼容性更好。
内容的提问来源于stack exchange,提问作者anand
相关产品推荐
相关产品推荐

