Hello, I'm Java beginner. I'm trying to use JPA with Hibernate and I've got an issue that I don't understand. It seems to me I found a bug, but maybe I'm doing something wrong.
For example I have two entities with OneToOne relation and EntityGraph to minimize queries count.
Code:
@Entity
@Data
public class Department {
@Id
@GeneratedValue
private long id;
private String name;
@OneToMany(mappedBy = "department")
private List<Person> persons;
@OneToOne
private DepartmentType type;
@Override
public String toString() {
return "Department id=" + this.id + " " + this.name;
}
}
@Entity
@NamedQuery(name = "departmetTypes",
query = "select dt from DepartmentType dt",
hints = {@QueryHint(name=QueryHints.HINT_LOADGRAPH, value = "DepartmentType.withDepartments")}
)
@NamedEntityGraph(name="DepartmentType.withDepartments", attributeNodes={@NamedAttributeNode("department")})
@Data
public class DepartmentType {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToOne(mappedBy="type")
private Department department;
}
The following code gives only one query (as I wish)
Code:
public static void main(String[] args) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
EntityGraph gr = em.getEntityGraph("DepartmentType.withDepartments");
em.createQuery("from DepartmentType", DepartmentType.class).setHint(QueryHints.HINT_LOADGRAPH, gr).getResultList().forEach(
dt-> System.out.println(dt.getDepartment())
);
em.getTransaction().commit();
}
Named query gives N+1 queries
Code:
public static void main(String[] args) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.createNamedQuery("departmetTypes", DepartmentType.class).getResultList().forEach(
p-> System.out.println(p.getDepartment()));
em.getTransaction().commit();
}
But named query with manually setted hint works correctly
Code:
public static void main(String[] args) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.createNamedQuery("departmetTypes", DepartmentType.class)
.setHint(QueryHints.HINT_LOADGRAPH, em.getEntityGraph("DepartmentType.withDepartments"))
.getResultList().forEach(
p-> System.out.println(p.getDepartment()));
em.getTransaction().commit();
}
bun it looks like overhead. Can I use NamedQueries with EntiTyGraph hint?
Sorry for my English.