richarbernal
richarbernal

Reputation: 1059

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?

Upvotes: 5

Views: 359

Answers (1)

JB Nizet
JB Nizet

Reputation: 691785

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;

Upvotes: 4

Related Questions