Hibernate is offering a configuration called LazyCollectionOption.EXTRA. Extra lazy collections means we can apply trivial operations to them without having to retrieve them from the database and without having to write these trivial queries to avoid doing so. Trivial operations are considered the size(), isEmpty() and contains(). If for example we have an entity User and an extra lazy collection called Address we can call user.getAddress.size() and this will generate a COUNT query on the ADDRESS table. So, no need to write a special query or load in memory the collection.
Lazy loading is set by default to @OneToMany relations but you need to set it on @ManyToOne which are by default Eagerly loaded. @OneToOne can be lazy loaded only if the relation is not optional. If the relation is optional the the proxy will have to query the database to find out if it should be null or if it should be initiated.
A spring boot property that needs to be overriden in all our applications because it is considered as an anti-pattern is the open-session-in-view (OSIV). This is a property that conveniently tackles all the LazyLoadingExceptions but at a high price. This property creates a Session that remains open even after the transaction is closed. It can be propagated over to the view layer where the code can produce queries to retrieve all lazily loaded associations on auto-commit mode. This is considered as an anti-pattern because the N+1 queries are causing congestion on the database connection pool and of course there is no separation of work.
Once the persistence context is closed, lazy loading is no longer available.
Lazy loading is set by default to @OneToMany relations but you need to set it on @ManyToOne which are by default Eagerly loaded. @OneToOne can be lazy loaded only if the relation is not optional. If the relation is optional the the proxy will have to query the database to find out if it should be null or if it should be initiated.
A spring boot property that needs to be overriden in all our applications because it is considered as an anti-pattern is the open-session-in-view (OSIV). This is a property that conveniently tackles all the LazyLoadingExceptions but at a high price. This property creates a Session that remains open even after the transaction is closed. It can be propagated over to the view layer where the code can produce queries to retrieve all lazily loaded associations on auto-commit mode. This is considered as an anti-pattern because the N+1 queries are causing congestion on the database connection pool and of course there is no separation of work.
Once the persistence context is closed, lazy loading is no longer available.
Comments
Post a Comment