hibernate 如何使用CriteriaQuery从子对象获取子列表?

xlpyo6sf  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(132)

我有两个型号:

模范方言家

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

货物模型

@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;
    
}

我正在尝试加载函数师,并急切地从Cargo获取CargotreinamentosNecessarios。我现在的代码可以带Cargo,但找不到treinamentosNecessarios
如何告诉CriteriaQueryCargo获取treinamentosNecessario集合?
以下是我的代码:

@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();
        }
    }
}
vlju58qv

vlju58qv1#

您可以这样做:

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

另请参阅Hibernate文档的这一部分。

相关问题