Dynamic query using JPQL

Asked

Viewed 390 times

0

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

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

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

Tables are being managed by the respective Entities:

Projectntity contains the attribute "coordinator"
Planoentregaentity contains the attribute "supplier"
Entregaentity contains the attribute "initial date" and "final date".

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 will be grateful.

  • But this search will return a list of which entity (Projectntity, Planoentregaentity or Entregaentity)?

1 answer

1

I’ll leave you an idea that you can try to improve. Hibernate has a feature that allows you to 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 parameter and return a Criterion to use in the queries. Follow 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();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.