简体   繁体   中英

How to use MySQL functions in Hibernate Criteria Query

I am wrting a JAVA background job that runs everyday near midnight and check all the persons in the database who will have birthday tomorrow and sending an auto greeting email to them.

I know how to write the native query but having difficulty in wrting that in Hibernate Criteria query. So, I need to translate a native MySQL query to equivalent JPA criteria query.

SimpleDateFormat birthdayFormatter = new SimpleDateFormat("MMdd");
String birthDay = birthdayFormatter.format(tomorrow); 

Native Query : select * from person WHERE DATE_FORMAT(birthday, '%m%d') = birthDay;

In Hibernate Criteria I have :

Criteria criteria = createCriteria();
criteria.add(Restrictions.eq("DATE_FORMAT(birthday, '%m%d')", birthDay));

That doesn't work . I also tried : Restrictions.sqlRestriction("DATE_FORMAT(birthday, '%m%d') = '" + birthDay + "'");

That also doesn't work.. Appreciate any advices..

So I finally found out a way from this link : stackoverflow.com/questions/2345419/

I need to use Restrictions.sqlRestriction() like so :

criteria criteria = createCriteria(); criteria.add(Restrictions.sqlRestriction("DATE_FORMAT({alias}.birthday, '%m%d') = ?", birthDay, StringType.INSTANCE));

That works !!

Check below code, how to write Creteria Query according to your requirement:

        @PersistenceContext
        EntityManager em; 

        CriteriaBuilder cb=em.getCriteriaBuilder();
        //select * from person  
        CriteriaQuery<person> qry =cb.createQuery(person.class);
        Root root = qry.from(person.class);  

        // WHERE DATE_FORMAT(birthday, '%m%d') = birthDay  
        Predicate predicate = cb.like(root.get("DATE_FORMAT"), "%"+birthday+"%");  
qry.where(predicate);

TypedQuery<person> tq = em.createQuery(qry);  
return tq.getResultList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM