Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

java - CriteriaQuery month and year filter

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) 
    );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...