I tried to experiment with the examples:
Student.class
@Entity
@NamedEntityGraph(
name = "Student.guide",
attributeNodes = {
@NamedAttributeNode("guide")
}
)
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID")
private Long id;
@Column(name="enrollment_id", nullable=false)
private String enrollmentId;
private String name;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name="guide_id")
private Guide guide;
...
Guide class:
@Entity
public class Guide {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID")
private Long id;
@Column(name="staff_id", nullable=false)
private String staffId;
private String name;
private Integer salary;
@OneToMany(mappedBy="guide", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private Set<Student> students = new HashSet<Student>();
...
Client class:
public class MergeDetachedClient2 {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello-world");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
EntityGraph<?> entityGraph = em.getEntityGraph("Student.guide");
Map<String, Object> properties = new HashMap<>();
properties.put("jakarta.persistence.fetchgraph", entityGraph);
Student student = em.find(Student.class, 10L, properties);
System.out.println(student);
Guide guide = student.getGuide();
System.out.println(guide);
em.getTransaction().commit();
em.close();
guide.setSalary(4500);
student.setName("Olga MiddleName1 Brown");
EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();
Student mergedStudent = em2.merge(student);
em2.getTransaction().commit();
em2.close();
}
}
So, here I used EntityGraphs to solve N+1 select problem in EntityManager1
but when I merged student in EntityManager2
I got select statement (the red border in screenshot) which I can’t understand “What for is it?” Please, help me to understand it :). I thought when we use merge()
method, one select statement will be issued to the database (with join operator to fetch related entities)