我有两个模型:
模型Funcionarios
@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
获取Cargo
和treinamentosNecessarios
。我现在的代码可以找到Cargo
,但是找不到treinamentosNecessarios
。
如何告诉CriteriaQuery
从Cargo
获取treinamentosNecessariosSet ?
下面是我的代码:
@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();
}
}
}
你可以这样做:
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文档的这一部分。