0gam
fetch=FetchType.LAZY and EAGER 본문
fetch=FetchType.LAZY
프로젝트 중
JPA LAZY 에러에 대해 생각해 보았다.
@OneToMany // @ManyToOne
엔티티를 select 할 때, 그와 연결된 관계를 왜 찾지 않는 것인가?
Lazy loading 때문이다.
Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used. The opposite of lazy loading is eager loading.
그래서 lazy 에러가 나는 것이다.
해서 해당 엔티티에 fetch=FetchType.EAGER를설정하면 그(엔티티) 와 연관된 관계를 모두 찾게 된다.
에러는 사라지고, 잘 돌아가지만.
쓸때없이 일을 열심히 해도 문제이고, 게으르게 일을 해도 문제이다.
해서 사용자가 이 이유와 쓰임을 알고 사용하게 된다면 좋을 것 같다.
끝.
* 기본 fetch 전략.
@ManyToOne , @OneToOne = eager
@OneToMany, @ManyToMany = lazy
How to Enable Lazy Loading in Hibernate
Before moving further, it is important to recap the default behavior of lazy loading in case of using hibernate mappings vs annotations.
The default behavior is to load ‘property values eagerly’ and to load ‘collections lazily’. Contrary to what you might remember if you have used plain Hibernate 2 (mapping files) before, where all references (including collections) are loaded eagerly by default. Also note that @OneToMany and @ManyToMany associations are defaulted to LAZY loading; and @OneToOne and @ManyToOne are defaulted to EAGER loading. This is important to remember to avoid any pitfall in future.
To enable lazy loading explicitly you must use "fetch = FetchType.LAZY" on a association which you want to lazy load when you are using hibernate annotations.
An example usage will look like this:
@OneToMany( mappedBy = "category", fetch = FetchType.LAZY ) private Set products; Another attribute parallel to "FetchType.LAZY" is "FetchType.EAGER" which is just opposite to LAZY i.e. it will load association entity as well when owner entity is fetched first time.
How Lazy Loading Works in Hibernate
The simplest way that Hibernate can apply lazy load behavior upon your entities and associations is by providing a proxy implementation of them. Hibernate intercepts calls to the entity by substituting a proxy for it derived from the entity’s class. Where the requested information is missing, it will be loaded from the database before control is ceded to the parent entity’s implementation.
Please note that when the association is represented as a collection class, then a wrapper (essentially a proxy for the collection, rather than for the entities that it contains) is created and substituted for the original collection. When you access this collection proxy then what you get inside returned proxy collection are not proxy entities; rather they are actual entities. You need not to put much pressure on understanding this concept because on runtime it hardly matters.
'Hibernate, JPA' 카테고리의 다른 글
| JPA Cascade Types (0) | 2018.05.30 |
|---|---|
| JPA, cascade (0) | 2016.07.07 |
| javax.persistence.Transient; (0) | 2016.06.24 |