19 Haziran 2018 Salı

JPA @NamedEntityGraphs Anotasyonu

Giriş
Şu satırı dahil ederiz.
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
Örnek
Elimizde şöyle bir kod olsun.
@NamedEntityGraphs({
    @NamedEntityGraph(
            name = "graph.father.setOfChildrens", 
            attributeNodes = @NamedAttributeNode(value = "setOfChildrens")),
})

@Entity
@Table
public class Father {
  ...

  @OneToMany(mappedBy = "father") // children
  private Set<Children> setOfChildrens;
  ...
}
Çağırmak için şöyle yaparız.
public List<Father> getAllFathersWithChildrensUsingEntityGraph() {

  CriteriaBuilder builder = entityManager.getCriteriaBuilder();
  CriteriaQuery<Father> criteriaQueryForFatherDTOs = builder.createQuery(Father.class);
  Root<Father> rootForFather = criteriaQueryForFatherDTOs.from(Father.class);
  criteriaQueryForFatherDTOs.select(rootForFather).distinct(true);
  TypedQuery<Father> typedQuery = entityManager.createQuery(criteriaQueryForFatherDTOs);
  EntityGraph graph = entityManager.getEntityGraph("graph.father.setOfChildrens");
  typedQuery.setHint("javax.persistence.fetchgraph",
    entityManager.getEntityGraph("graph.father.setOfChildrens"));
  List<Father> listOfFathers = typedQuery.getResultList();
  return listOfFathers;
}

Hiç yorum yok:

Yorum Gönder