Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using hibernate return count value of a query

Tags:

hibernate

this is my mysql query:

SELECT count(*) 
FROM bw_jobs 
WHERE year(job_date)=year(curdate()) AND month(job_date)=month(curdate());

How to use this in hibernate to get count value?

like image 913
Sureshkumar Menon Avatar asked May 01 '11 13:05

Sureshkumar Menon


1 Answers

String hql = "select count(job.id) from Job job"
             + " where year(job.jobDate) = year(current_date())"
             + " and month(job.jobDate) = month(current_date())";
Query query = session.createQuery(hql);
return ((Number) query.uniqueResult()).intValue();

(assuming the bw_jobs table is mapped by the Job entity, and the job_date column is mapped to the jobDate property)

See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#queryhql-expressions for the list of functions supported by Hibernate.

like image 154
JB Nizet Avatar answered Dec 10 '22 11:12

JB Nizet