Search code examples
hibernatejpatransactionslazy-loadingentitymanager

Hibernate loads all entities ignoring LAZY load


My application uses Hibernate to retrieve data from database. Today I have debugged my application and stumbled upon EAGER load.

@Table(name = "orders")
@Entity
public class Order implements Serializable {
@OneToMany(fetch = FetchType.EAGER, mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
        private List<DishQuantity> dishes = new ArrayList<>();
}

I changed it to LAZY load like this:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<DishQuantity> dishes = new ArrayList<>();

When I make a call to database from service using DAO I receive result as expected, lazily loaded entities are no longer available:

lazy loading from service

But when I'm going down to query and trying to get entity using Entity Manager I receive this:

enter image description here

It looks like Hibernate anyway loads all entities but after transaction is closed, LAZY entities are discarded, right? But anyway it got all entities from DB and haven't improved DB performance at all. Is there a way to force Hibernate don't load LAZY entities even during transaction and reduce DB load?


Solution

  • They are loaded lazily in both cases, but you are triggering initialization in the debugger (first time after the enclosing Session is closed, the second time during an active Session).

    You can enable SQL logging to check which queries are executed in the db.