Home > OS >  How to eagerly fetch a child list from a child object using CriteriaQuery?
How to eagerly fetch a child list from a child object using CriteriaQuery?

Time:11-11

I have two models:

Model Funcionarios

@Entity
@Table(name = "funcionarios")
public class Funcionario extends Model {
    
    ....
    
    @NotFound(action = NotFoundAction.IGNORE)
    @ManyToOne(fetch = FetchType.LAZY, optional = true)
    private Cargo cargo;
    ...
    
}

Model Cargos

@Entity
@Table(name = "cargos")
public class Cargo extends Model {
    
    @Column(nullable = false, unique = true, columnDefinition = "TEXT")
    private String cargo = "";
    
    
    @ManyToMany(fetch = FetchType.LAZY)
    private Set<Treinamento> treinamentosNecessarios;
    
}

I'm trying to load funcionarios and eagerly fetching Cargo and treinamentosNecessarios from Cargo. My current code can bring Cargo but cannot find treinamentosNecessarios.

How do I tell CriteriaQuery to Fetch treinamentosNecessarios Set from Cargo?

Here's my code:

@Override
public Funcionario find(Long id, Session session, boolean closeSession) {
    try {
            
        CriteriaBuilder cb = session.getCriteriaBuilder();
    
        CriteriaQuery<Funcionario> criteriaQuery = cb.createQuery(Funcionario.class);
    
        Root<Funcionario> root = criteriaQuery.from(Funcionario.class);
        root.fetch("avaliacoes", JoinType.LEFT);
        root.fetch("treinamentosRealizados", JoinType.LEFT);
        root.fetch("cargo", JoinType.LEFT);
            //root.fetch("cargo.treinamentosNecessarios", JoinType.LEFT);
    
        criteriaQuery.select(root);
        criteriaQuery.where(cb.equal(root.get("id"), id));
    
        Query<Funcionario> query = session.createQuery(criteriaQuery);
    
        Funcionario singleResult = query.getSingleResult();
        return singleResult;
    
    } catch (Exception ex) {
        throw ex;
    } finally {
        if (session != null && closeSession) {
            session.close();
        }
    }
}

CodePudding user response:

You can do something like this:

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Fetch;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Root;
import org.hibernate.query.Query;

// ...

CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Funcionario> criteriaQuery = cb.createQuery(Funcionario.class);

Root<Funcionario> root = criteriaQuery.from(Funcionario.class);
Fetch<Cargo, Funcionario> cargoFetch = root.fetch("cargo", JoinType.LEFT);
cargoFetch.fetch("treinamentosNecessarios", JoinType.LEFT);

criteriaQuery.select(root);
criteriaQuery.where(cb.equal(root.get("id"), 2L));

Query<Funcionario> query = session.createQuery(criteriaQuery);
Funcionario func = query.getSingleResult();

See also this part of the hibernate documentation.

  • Related