Question

Here is my hibernate POJO classes.

@Entity
@Table(name = "PARENT")
public class Parent {

  @Id
  private int id;

  @Column(name = "NAME")
  private String name;

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
  private List<Child> children;

  // Getters and Setters...
}

@Entity
@Table(name = "CHILD")
public class Child {

  @Id
  private int id;

  @Column(name = "NAME")
  private String name;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "PARENT_ID", nullable = false)
  private Parent parent;

  // Getters and Setters...
}

Here are two ways, from what I've learned about hibernate. (I'm still noob :P)

  Session session = sessionFactory.openSession();
  List<Child> children = null;

  try {
     children = session.createCriteria(Child.class, "C")
                  .add(Restrictions.eq("C.parent", parent)
                  .list();
  } finally {
    session.close();
  }

Or

  Session session = sessionFactory.openSession();
  List<Child> children = null;

  try {
     session.refresh(parent);
     children = parent.getChildren();
  } finally {
    session.close();
  }

The later one which is using refresh, I found out accidentally while experimenting with Hibernate.

Q.1 What is the best way?

Q.2 Why use Criteria API or HQL to get lazy load members, when you can get all children just by calling the getter method?

Was it helpful?

Solution

You can load children by calling getter method only if the parent object is attached to session. You can attach an object to session through either loading it (what calling refresh does on above code) or saving or updating; see documentation for more explanation. Like following code:

Session s = getSession();
Parent parent = s.get(parent, id);
List children = parent.getChildren();

And doing this basically is same as using criteria API (the way you have used). Criteria and HQL are used for a big variety of other things. In your case there is no point on using them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top