Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to lazy load for a non lazy relationship in Hibernate?

I've got a parent-child relationship with the lazy attribute set false, so when I get the parent class with a query I obtain his children too.

It is usually preferable to load everything, parent-children, but in one case I need not to do this.

Is there a way to avoid fetch the children when I get the parent without altering the lazy=false relationship?

like image 360
richarbernal Avatar asked Oct 07 '22 17:10

richarbernal


1 Answers

No, it's not possible. The only thing you can do if you just have one case where the association must not be fetched is to use a DTO instead of your entity, and use projections to retrieve only what you want:

String hql = "select firstName, lastName from User u where ...";
List<Object[]> rows = session.createQuery(hql).list();
List<UserDTO> users = new ArrayList<UserDTO>(rows.size());
for (Object[] row : rows) {
    users.add(new User((String) row[0], (String) row[1]));
}
return users;
like image 177
JB Nizet Avatar answered Oct 12 '22 12:10

JB Nizet