怠惰なフェッチ


私は理論的に怠惰なことを知っている。現実世界のシナリオで教えて!


Consider an online store, which is a standard Internet web application. A product catalog is kept at the store. This may be depicted as a catalog entity handling a collection of product entities at the most basic level. There might be tens of thousands of goods divided into many overlapping categories in a large store.
The catalog must be loaded from the database when a consumer enters the store. We presumably don't want the implementation to load each and every one of the entities that represent the tens of thousands of goods into memory. Given the amount of physical memory available on the system, this may not even be practical for a sufficiently big store.
Even if this were possible, the site's performance would almost certainly suffer as a result. Instead, we'd like the catalog to load first, followed by the categories. Only a fraction of the goods in each category should be loaded from the database when the user digs down into the categories.
Hibernate includes a feature called lazy loading to address this issue. When enabled, the associated entities of an entity will only be loaded when they are specifically requested.


どのように'怠惰'上記の問題を解決できますか?🐌


以下のようにしてください.
//Following code loads only a single category from the database
Category category = (Category)session.get(Category.class,33);

//This code will fetch all products for category 33 from database
Set<Product> products = category.getProducts();
これは問題を解決します?現在、Hibernateはあなたのためにそれを作ります..以下のコードスニペットを見てください.
@OneToMany( mappedBy = "category", fetch = FetchType.LAZY )
private Set<ProductEntity> products; 

まとめる


長所
  • は、他のアプローチ
  • よりもはるかに小さい初期負荷時間である
    他のアプローチよりも少ないメモリ消費量
    短所
  • 遅れた初期化は、不要な瞬間の間にパフォーマンスに影響を与えるかもしれません.
  • 場合によっては、特別な注意を払ってlazily初期化オブジェクトを処理する必要があります.(次のポストで説明する)