When to use lazy initialization and when Eager as even if we do lazy then the variable which we will use will still contain some data associated with the following task. So how do we choose between both? Are there any performance and memory efficient differences between the both?
Please explain any best use case as some threads are supporting eager and some lazy.
In general, the advantages of lazy loading are:
And the disadvantages are:
In other languages another disadvantage is extra code to implement that last bit, but Kotlin's by lazy
makes it ridiculously easy!
Obviously the overall benefit depends on how likely you are to need the value at all, and the impact of a delay at start-up compared to later on.
The first thing that we should discuss here is what lazy loading and eager loading are:
Eager Loading is a design pattern in which data initialization occurs on the spot Lazy Loading is a design pattern which is used to defer initialization of an object as long as it's possible Let's see how this actually works with some examples:
The UserLazy class:
@Entity
@Table(name = "USER")
public class UserLazy implements Serializable {
@Id
@GeneratedValue
@Column(name = "USER_ID")
private Long userId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<OrderDetail> orderDetail = new HashSet();
// standard setters and getters
// also override equals and hashcode
}
The OrderDetail class:
@Entity
@Table (name = "USER_ORDER")
public class OrderDetail implements Serializable {
@Id
@GeneratedValue
@Column(name="ORDER_ID")
private Long orderId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="USER_ID")
private UserLazy user;
// standard setters and getters
// also override equals and hashcode
}
One User can have multiple OrderDetails. In eager loading strategy, if we load the User data, it will also load up all orders associated with it and will store it in a memory.
But, when lazy loading is enabled, if we pull up a UserLazy, OrderDetail data won't be initialized and loaded into a memory until an explicit call is made to it.
In the next section we will see how the above example is implemented in Hibernate.
Find the article here: https://www.baeldung.com/hibernate-lazy-eager-loading
And read this also: https://www.imperva.com/learn/performance/lazy-loading/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.