How to search date field for a String using JPA Criteria API

前端 未结 3 980
孤街浪徒
孤街浪徒 2021-01-06 13:00

This is a question that spins off my other Question here . I thought it would be best put as a different question after someone(@Franck) pointed me to this link and this one

3条回答
  •  佛祖请我去吃肉
    2021-01-06 13:45

    Ok, after lots of experimenting with various strategies, here's what I did that finally worked.

    I saw this post here and suddenly remembered the JPA Tuple Interface which is an Object that can return multiple result Type(s). So to perform my like comparison, and since Date cannot be simply cast to a String here are the steps;

    1. I get the column as a Tuple
    2. do a check on The Tuple Object to see if it's assignable from Date
    3. if it is, then get the Date-Format expression and pass it to the like expression.

    So essentially, here's what I initially had which was apparently failing;

    predicates.add(cb.like(cb.lower(entity.get("dateJoined").as(String.class)), "%"+search.toLowerCase()+"%")); 
    

    Now, this is what I have that works beautifully;

    Path tuple = entity.get("dateJoined");
    if(tuple.getJavaType().isAssignableFrom(Date.class)){
        Expression dateStringExpr = cb.function("DATE_FORMAT", String.class, entity.get("dateJoined"), cb.literal("'%d/%m/%Y %r'"));
        predicates.add(cb.like(cb.lower(dateStringExpr), "%"+search.toLowerCase()+"%"));
    }
    

    NOTE-WORTHY CONSIDERATIONS -

    1. I am aware that from wherever the search would be initiated, all my Dates are presented in this form 07/10/2015 10:25:09 PM hence my ability to know how to format the Date for the comparison in my like expression as "'%d/%m/%Y %r'".
    2. This is just one step that works for Dates. Most other Types e.g int, long, char ...etc... can all be directly Cast to String and as I explore more Types of data, I'll definitely do the same for any other Type that cannot be directly Cast to String.

    Though this works perfectly for me, but before I mark this as the right answer, I'm going to subject it to some more extensive tests and in the process keep it open for comments by anyone that has any reservations about my strategy.

    And finally, to that one person that this helped out in any way... Cheers!

提交回复
热议问题