Dynamic query using JPQL

0

I need to implement a dynamic query logic, in the DB using JPQL, and I have 4 filters:

  

1 - PROJECT COORDINATOR
  2 - SERVICE PROVIDER
  3 - DATE START OF THE PROJECT
  4 - FINAL DATE OF THE PROJECT

Any of the fields can be combined together, that is, COORDINATOR and INITIAL DATE, SUPPLIER and INITIAL DATE can be selected, and so on ...

The tables are being managed by their Entities:

  

ProjectEntity contains the attribute "coordinator"
  PlanEntityEntity contains the attribute "provider"
EntregaEntity   contains the attribute "datainicial" and "datafinal".

I tried to implement Criteria (uaihebert, easycriteria, criteriabuilder and etc), but I did not have much success, if anyone has any indication, even initial wue, I'll be grateful.     

asked by anonymous 23.12.2016 / 15:01

1 answer

1

I'll leave you an idea that you can try to hone. Hibernate has a feature that lets you create a query from an instance: org.hibernate.criterion.Example . Since you already have the entities, just set the values you want to search in the entity itself and create a function to receive it as a parameter and return a Criterion to use in the queries. Here's the example below:

public Criterion criarCriteria(Object projeto) {
    Criterion retorno = null;
    if (projeto != null) {
        retorno = Example.create(projeto)
                        .ignoreCase()
                        .enableLike(MatchMode.ANYWHERE);
    }
    return retorno;
}

@SuppressWarnings("unchecked")
public List<ProjetoEntity> consultarProjeto(ProjetoEntity projeto, PlanoEntregaEntity planoEntrega, EntregaEntity entrega) {
    DetachedCriteria criteria = DetachedCriteria.forClass(ProjetoEntity.class);

    Criterion criterionProjeto = this.criarCriteria(projeto);
    if (criterionProjeto != null) {
        criteria.add(criterionProjeto);
    }

    Criterion criterionPlanoEntrega = this.criarCriteria(planoEntrega);
    if (criterionPlanoEntrega != null) {
        DetachedCriteria criteriaPlanoEntrega = DetachedCriteria.forClass(PlanoEntregaEntity.class);
        criteriaPlanoEntrega.add(criterionPlanoEntrega);
        criteriaPlanoEntrega.setProjection(Projections.property("id"));
        criteria.add(Property.forName("planoEntrega").in(criteriaPlanoEntrega));
    }

    Criterion criterionEntrega = this.criarCriteria(entrega);
    if (criterionEntrega != null) {
        DetachedCriteria criteriaEntrega = DetachedCriteria.forClass(EntregaEntity.class);
        criteriaEntrega.add(criterionEntrega);
        criteriaEntrega.setProjection(Projections.property("id"));
        criteria.add(Property.forName("entrega").in(criteriaEntrega));
    }

    return criteria.getExecutableCriteria(this.getSession()).list();
}
    
28.12.2016 / 17:04