5

I'm trying to make a criteria query (JPA/Hibernate)in a model which contain one column with date (Oracle 11G) . For example, i have

  1. 13-JAN-09
  2. 15-JAN-09
  3. 16-MAR-09

And my function is like:

public MyEntity getEntitiesFromCertainFilters(int a, int b, java.util.date c)
{
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery< MyEntity > query = builder.createQuery(MyEntity.class);
    Root< MyEntity > root = query.from(MyEntity.class);

    query.select(root).where (
        builder.equal ( root.get ( "id" ).get ( "codEstablec" ) , establecimiento),
        builder.equal ( root.get ( "id" ).get ( "correlGrupo" ) , correlGrupo),
        //HERE I NEED TO ADD FILTER BY C.MONTH AND C.YEAR FROM THE DATE ATTRIBUTE
        );

    List < MyEntity > resultList = entityManager.createQuery(query).getResultList();  
    return resultList.get(0);
}

If i want to filter by c = "01-JAN-09", it should return:

  1. 13-JAN-09
  2. 15-JAN-09

Any help would be really appreciated, thanks in advance.

Rcordoval
  • 1,932
  • 2
  • 19
  • 25

2 Answers2

13

You can use the builder.function method. E.g.

query.select(root).where (
    builder.equal ( root.get ( "id" ).get ( "codEstablec" ) , establecimiento),
    builder.equal ( root.get ( "id" ).get ( "correlGrupo" ) , correlGrupo),
    builder.equal(builder.function("YEAR", Integer.class, root.get("DATE_FIELD") ), C.YEAR),
    builder.equal(builder.function("MONTH", Integer.class, root.get("DATE_FIELD")), C.MONTH) 
    );
tharanga-dinesh
  • 537
  • 6
  • 26
  • Wow. I forgot about this project (2017). But i checked the source and i did what you posted. `builder.equal(builder.function("month", Integer.class, root.get("id").get("anoMes")), mes),` A bit late but i'll give you the acceptance. Cheers! – Rcordoval Sep 27 '18 at 06:42
1

I assume you're getting your date values like this question.

Rather than making a messy query comparing individual parts of dates, just create two encompassing queries.

Date c; //this is your provided date.
Date d; //this is your endpoint.

d = new Date(c.getTime());
d.setMonth(d.getMonth()+1); // creates 01FEB09

From then, all you need to do is find dates GREATERTHANOREQUALTO c and LESSTHAN d.

Community
  • 1
  • 1
Compass
  • 5,867
  • 4
  • 30
  • 42