Hibernate Lazy Loading: Configuration Guide
In Hibernate, lazy loading can be achieved through configuration files or annotations.
- Implement lazy loading through configuration file.
In Hibernate configuration file (usually hibernate.cfg.xml), lazy loading can be implemented by setting lazy=”true”. For example:
<property name="hibernate.enable_lazy_load_no_trans">true</property>
After this configuration, Hibernate will load data from the database only when the lazy-loaded property is used.
- Implement lazy loading using annotations.
Using the @Basic(fetch = FetchType.LAZY) annotation on entity class properties enables lazy loading. For example:
@Basic(fetch = FetchType.LAZY)
private List<Item> items;
After this configuration, Hibernate will lazily load data from the database when the items property is accessed.
It should be noted that lazy loading can lead to N+1 query issues, so it is important to be cautious when using lazy loading to prevent this problem from occurring.