IT

최대 절전 모드에서 지연 로딩이란 무엇입니까?

lottoking 2020. 5. 27. 07:56
반응형

최대 절전 모드에서 지연 로딩이란 무엇입니까?


Java에서 지연 로딩이란 무엇입니까? 과정을 이해하지 못합니다. 아무도 게으른 로딩 과정을 이해하도록 도울 수 있습니까?


부모님이 있고 그 부모에게 자녀 모음이 있다고 가정하십시오. 최대 절전 모드는 이제 자식을 "지연로드"할 수 있으므로 부모를로드 할 때 실제로 모든 자식을로드하지는 않습니다. 대신 요청이있을 때로드합니다. 이것을 명시 적으로 요청하거나 훨씬 더 일반적으로 할 수 있으며, 최대 절전 모드는 자식에 액세스하려고 할 때 자동으로로드됩니다.

지연 로딩은 종종 자식이 필요하지 않으므로로드되지 않기 때문에 성능을 크게 향상시키는 데 도움이됩니다.

n + 1 문제도주의하십시오. 최대 절전 모드는 컬렉션에 액세스 할 때 실제로 모든 자식을로드하지 않습니다. 대신 각 자식을 개별적으로로드합니다. 컬렉션을 반복 할 때 모든 자식에 대한 쿼리가 발생합니다. 이를 피하기 위해, 예를 들어 parent.getChildren (). size ()를 호출하여 모든 자식을 동시에로드하도록 최대 절전 모드를 속일 수 있습니다.


"게으른로드"는 실제로 엔티티에 처음 액세스 때만 엔티티가로드됨을 의미합니다 .

패턴은 다음과 같이이다 :

public Entity getEntity() {
    if (entity == null) {
        entity = loadEntity();
    }
    return entity;
}

이 / 미리로드 미리 입력의 비용을 절약 할 수 있는 모든에게 모든 사실 필요가 없습니다 후 동안 미리 큰 데이터 세트에서 엔티티를 모두 그들 중입니다.

최대 절전 모드에서 하위 엔터티 컬렉션을 느리게로드하도록 구성 할 수 있습니다. 실제 지연로드는 다음의 방법 안에 완료 PersistentSet"후드 아래"하는 최대 절전 모드 사용 등 개체의 컬렉션을 지정합니다 Set.

예 :

public class Parent {
    private Set<Child> children;

    public Set<Child> getChildren() {
        return children;
    }
}

.

public void doSomething() {
    Set<Child> children = parent.getChildren(); // Still contains nothing.

    // Whenever you call one of the following (indirectly), 
    // Hibernate will start to actually load and fill the set.
    children.size();
    children.iterator();
}

Martin Fowler는 다음 과 같이 엔터프라이즈 애플리케이션 아키텍처 패턴에서 지연로드 패턴을 정의합니다 .

필요한 모든 데이터를 포함하지는 않지만 가져 오는 방법을 알고있는 객체입니다.

따라서 주어진 객체를로드 할 때 관련 성능 비용을 절약하기 위해 즉시 사용할 수없는 관련 객체를 열망 하지 않는 것이 좋습니다 . 대신 관련 개체가 사용될 때만로드됩니다.

이것은 데이터 액세스 및 최대 절전 모드에 특정한 패턴은 아니지만 이러한 필드에서 특히 유용하며 최대 절전 모드는 일대 다 연결 및 단일 지점 연결 (일대일 및 다 대일)의 지연로드를 지원합니다. 특정 조건에서. 게으른 상호 작용에 대해서는 Hibernate 3.0 Reference Documentation의 19 장 에서 더 자세히 설명 합니다.


지연 로딩은 기본적으로 true입니다. 지연 로딩은 선택 쿼리가 실행될 때 데이터베이스에 도달하지 않음을 의미합니다. getter 함수를 기다릴 것입니다. 즉, 필요할 때 datbase에서 가져옵니다. 예를 들어, 당신은 장난감이 많은 아이를 가진 부모입니다. 그러나 현재 문제는 당신이 그를 부를 때마다 (우리는 당신이 소년이 있다고 가정합니다), 그는 모든 장난감을 가지고 당신에게옵니다. 이제는 장난감을 항상 가지고 다니는 것을 원하지 않기 때문에 이것은 문제입니다. 따라서 합리적 인 부모이기 때문에 바로 어린이의 장난감을 LAZY로 정의하십시오. 이제 당신이 그를 부를 때마다, 그는 장난감없이 당신에게 온다.


지연 가져 오기는 상위 오브젝트를로드하는 동안 하위 오브젝트를로드할지 여부를 결정합니다. 부모 클래스의 각 최대 절전 모드 매핑 파일에서이 설정을 수행해야합니다. Lazy = true(자식을로드하지 않음을 의미) 기본적으로 자식 오브젝트의 지연로드는 true입니다.

이것은 부모 객체에서 getChild()메소드를 호출하여 응용 프로그램에서 명시 적으로 호출하지 않는 한 자식 객체가로드되지 않도록합니다.이 경우 최대 절전 모드 getChild()는 부모 객체 에서 실제로 호출 될 때 자식을로드하기 위해 새로운 데이터베이스 호출을 발행 합니다.

그러나 경우에 따라 부모가로드 될 때 자식 개체를로드해야합니다. lazy = false로 설정하면 부모가 데이터베이스에서로드 될 때 최대 절전 모드에서 자식을로드합니다.

예 : TABLE이 있다면? EMPLOYEE는 Employee 개체에 매핑되었으며 Address 개체 집합을 포함합니다. 부모 클래스 : 직원 클래스, 자식 클래스 : 주소 클래스

public class Employee { 
private Set address = new HashSet(); // contains set of child Address objects 
public Set getAddress () { 
return address; 
} 
public void setAddresss(Set address) { 
this. address = address; 
} 
} 

Employee.hbm.xml 파일에서

<set name="address" inverse="true" cascade="delete" lazy="false"> 
<key column="a_id" /> 
<one-to-many class="beans Address"/> 
</set> 

위 구성에서. 다음과 같은 경우 lazy="false":-해당 하위 개체 주소가 Employee 개체를로드 할 때 setAddresss () 메서드로 설정됩니다. employee.getAdress ()를 호출하면로드 된 데이터가 반환됩니다. 새 데이터베이스 호출이 없습니다.

If lazy="true":-기본 구성입니다. 언급하지 않으면 최대 절전 모드로 설정하면 lazy = true로 간주됩니다. 하위 오브젝트 Adress가로드되지 않은 시간에 Employee 오브젝트를로드 할 때 주소 개체를 얻으려면 데이터베이스를 추가로 호출해야합니다. 호출 employee.getAdress()하면 해당 시간 데이터베이스 쿼리가 실행되고 결과가 반환됩니다. 새로운 데이터베이스 호출.


In layman's language, it is like you are making a cake and you will need 5-10 ingredients from fridge. You have two options, get all ingredients from fridge and put it on your kitchen platform, or bring the item you want when you need.

Similarly, in eager loading, you fetch all information about bean and its related classes (not child or is-a relation but has a relationship, i.e. cake has flour, has milk, has cream etc), and in case of lazy loading, first you bring only its identifier and values that are coming from same table (necessary ingredients that first you will need in your bowl in case of cake). All information that is coming from other tables will be fetched as and when required/used.


Lazy Loading? Well, it simply means that child records are not fetched immediately, but automatically as soon as you try to access them.


Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object.But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.Exampleslazy=true (default)Address child of User class can be made lazy if it is not required frequently.lazy=falseBut you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.


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

Wikipedia

Link of Lazy Loading from hibernate.org


Well it simply means loading data you need currently instead of loading whole bunch of data at once which you won't use now. Thereby making application load time faster than usual.


Hiberante supports the feature of lazy initialization for both entities and collections. Hibernate engine loads only those objects that we are querying for does not other entites or collections.

lazy="false" by default loading initialization mention for the only child is lazy.in case of true that is parent is loading does not support child


Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazy loading of the child objects is true.


Surprisingly, none of answers talk about how it is achieved by hibernate behind the screens.

Lazy loading is a design pattern that is effectively used in hibernate for performance reasons which involves following techniques.


1. Byte code instrumentation:

Enhances the base class definition with hibernate hooks to intercept all the calls to that entity object.

Done either at compile time or run[load] time

1.1 Compile time

  • Post compile time operation

  • Mostly by maven/ant plugins

1.2 Run time

  • If no compile time instrumentation is done, this is created at run time Using libraries like javassist

2. Proxies

The entity object that Hibernate returns are proxy of the real type.

See also: Javassist. What is the main idea and where real use?


Lazy loading allows you to defer the association retrieval or to have a better control over the fetching strategy.

When you use EAGER loading, you define a global fetch plan which cannot be overridden at query time, meaning you are limited to a decision you took while designing your entity model. The EAGER fetching is a code smell, because the fetching strategy is a query-time policy and it might differ from a business use case to another.

The fetching strategy is a very important aspect, as too much EAGER fetching can cause serious performance related issues.

참고URL : https://stackoverflow.com/questions/2192242/what-is-lazy-loading-in-hibernate

반응형