Lazy load with ejb

zhaozj2021-02-11  185

Lazy load

An Object That Doesn't Contain All of the data you need, but know how to get it.

Class Supplier ...

Public List getProducts () {

IF (Products == NULL) Products = Product.FindForsupplier ());

Return Products;

}

As you load data from a database into memory it's handy to design things so that as you load an object of interest, you also load the objects that are related to that object. This makes loading easier on the developer using the object, who otherwise has TO EXPLICITLY LOAD All the Objects They NEED Themselves.

However if you take this to its logical conclusion, you reach the point where loading one object can have the effect of loading a huge amount of other related objects into the system, something that hurts performance when only a few of the objects are actually needed.

A Lazy Load interrupts this loading process for the moment, leaving a marker in the object structure so that if the data is needed it can be loaded only then. As many people know, if you're lazy about doing things you'll win when IT Turns Out you don't need to do them at all.

HOW it works

There Are Four Main Ways You CAN IMPLEMENT LAZY LOAD: Lazy Initialization, Virtual Proxy, Value Holder, And Ghost.

Lazy initialization [Beck-patterns] is the simplest one to do. The basic idea is that every access to the field checks first to see if it's null. If it's null it calculates the value of the field before returning the field. To make this .

Using a null to signal a field that has not been loaded yet works well, unless null is a legal value for the field. In this case you either need something else to signal the field has not been loaded, or to use a Special Case for the null value.Using lazy initialization is simple, but it does tend to force a dependency between the object concerned and the database so it works best for Active Record, Table Data Gateway, and Row Data Gateway. If you're using Data Mapper you'll need an additional layer of indirection. you can obtain this by using a virtual proxy [Gang of Four]. A virtual proxy is an object that looks like the object that should be in the field, but actually does not contain Anything. Only When ONE '$ Methods IS Called Does It loading The Correct Object from The Database.

The good thing about a virtual proxy is that looks exactly like the object that's supposed to be there. However it is not so you can easily run into a nasty identity problem. Often the virtual proxy is a different object to the real object. Furthermore you can have more than one virtual proxy for the same real object. All of these will have different object identities, yet they represent the same conceptual object. At the very least you have to override the equality method and remember to use it instead of an Identity Method. But without That, And Discipline, You'll Run Into Some Very Hard to TRACK BUGS.

In some environments the other problem with a virtual proxy is that you end up having to create lots of them, one for each class you are proxying. You can usually avoid this in dynamically typed languages, but with static type languages ​​things usually get messy. Even when the platform provides handy facilities, such as Java's proxies, they introduce other inconveniences.These problem do not hit you if you only use virtual proxies for collections classes, such as lists. Since collections are Value Objects, their identity does not .

With domain classes you can avoid these problems by using a value holder. The value holder concept, which I first came across in Smalltalk, is an object that wraps some other object. To get the underlying object you ask the value holder for its value. Only on the first access does it pull the data from the database. The disadvantages of the value holder is that the class needs to know there is a value holder present, and you lose the explicitness of strong typing. you can avoid identity problems by ensuring That The Value Holder Is Never Passed Out Beyond Its Owning Class.

A ghost is the real object, but not in its full state. When you load the object from the database it contains just its ID. Whenever you try to access a field it loads its full state from the database. You can think of a ghost as an object where every field is lazy initialized in one fell swoop, or as a virtual proxy where the object is its own virtual proxy. Of course there's no need to load all the data in one go, you may group the data into groups that are commonly used together. If you use a ghost you can put it immediately in its Identity Map. By doing this not just will you maintain identity, you'll also avoid all problems due to cyclic references when reading in data.When you use a virtual proxy or a ghost the proxy / ghost does not need to be completely devoid of data. If you have some data which is quick to get hold of and commonly used, it may make sense to load this data when you load the proxy or "this is some thing" referred to ask as a "light object".)

Inheritance often poses a problem with Lazy Load. If you're going to use ghosts, you'll need to know what type of ghost to create, which you often can not tell without loading the thing properly. Virtual proxies can suffer from the Same Problem in Static Typed Languages.

One danger with Lazy Load is that it can easily cause more database accesses then you need. A good example of this ripple loading is if you fill a collection with Lazy Loads and then look at them one at a time. This will cause you to go to the database once for each object, instead of reading them all in at once. I've seen ripple loading cripple the performance of an application. One way to avoid ripple loading is not to have a collection of Lazy Loads, rather make the collection itself a Lazy Load and when you load it load all the contents. The limitation of this tactic is when the collection is very large, such as all the IP addresses in the world. in practice these are not usually linked up through associations in the object model, so that does not happen very often. When it does you'll need a Value List Handler [missing reference] .Lazy Load is a good candidate for aspect-oriented programming. you can put the Lazy Load behavior into a separate Aspect, Which Allows you change the lazy Load Strategy Separately As Well As Freeing The Domain Developers from Having to Deal With Lazy Load Issues. I've Also Seen a Project Post-Process Java bytecode To Implement Lazy Load In a Transparent Way.

Often you'll run into situations where different use cases work best with a different variety of laziness. Some use cases need one subset of the object graph, others use a different subset. For maximum efficiency you want to load the right sub-graph for The Right Use Case.

The way to deal with this is to have separate database interaction objects for the different use cases. So if you use Data Mapper you may have two order mapper objects, one that loads the line items immediately, and one that loads the line items lazily. The application code chooses the appropriate mapper depending on the use case. A variation on this is to have the same basic loader object, but defer to a strategy object to decide the loading pattern. It's a bit more sophisticated but can be a better way to factor the behavior.In theory, you might want a range of different degrees of laziness, but in practice you really only need two:. a complete load and enough of a load for identification purposes in a list Adding more usually adds more complexity than is Worth while.

When to use it

Deciding when to use Lazy Load is all about deciding how much you want to pull back from the database as you load an object, and how many database calls it will require. It's pointless to use Lazy Load on a field that's stored in the same row as the rest of the object, because it does not cost any more to bring back extra data in a call, even if the data field is quite large: such as a Serialized LOB So it's only worth considering Lazy Load if the field requires. An Extra Database Call to Access.

In performance terms it's then about deciding when you want to take the hit of bringing back the data. Often it's a good idea to bring everything you'll need in one call so you have it in place, particularly if it corresponds to a single interaction WITH A UI. The Best Time To Use Lazy Load is When Not Just Dot, It's Also Data That Offense IS Used.

Adding lazy loading to the program. So my preference is to not use lazy loading unless I Actively Think I'll Need It.example: Lazy Initialization (Java)

The Essence of Lazy Initialization is Code Like this.

Class Supplier ...

Public List getProducts () {

IF (Products == NULL) Products = Product.FindForsupplier ());

Return Products;

}

.

EXAMPLE: Virtual Proxy (Java)

The key to the virtual proxy is to provide a class that looks like the actual class you would normally use, but actually holds a simple wrapper around the real class. So a list of products for a supplier would be held with a regular list field.

Class Suppliervl ...

PRIVATE LIST PRODUCTS;

The most complicated thing about producing a list proxy like this is setting it up so that you can provide an underlying list that's only created when it's accessed. To do this we have to pass the code that's needed to create the list into the virtual list when It's instantiated.

THE BEST WAY TO DO THIS in Java Is To Define An Interface for the Loading Behavior.

Public interface virtual meansloader {

List load ();

}

THEN We can instantiate the Virtual List with a loader That Calls the appropriate mapper method.

Class SupplierMapper ...

Public Static Class ProductLoader IMPLEments VirtualListLoader {

Private long id;

Public ProductLoader (long id) {

THIS.ID = ID;

}

Public List load () {

Return ProductMapper.create (). FindForsupPlier (ID);

}

}

During the loading method we assign the product loader to the list far

Class SupplierMapper ...

Protected DomainObject DOLOAD (long ID, resultset rs) throws sqlexception {string namearg = rs.getstring (2);

Suppliervl Result = New SupplierVL (ID, NameArg);

Result.SetProducts (New VirtuAllist (New ProductLoader (ID));

Return Result;

}

The Virtual List's Source List Is Self Encapsulated and Evaluates The Loader on First Reference

Class VirtualList ...

Private List source;

Private VirtualListLoader Loader;

Public VirtualList (VirtualListLoader Loader) {

This.Loader = loading;

}

Private list getsource () {

IF (source == null) source = loadinger.load ();

Return Source;

}

I THEN IMPLEMENT THE REGULAR LIST METHODS To Delegate to the source list.

Class VirtualList ...

Public int size () {

Return getSource (). size ();

}

Public Boolean ISempty () {

Return getSource (). ISempty ();

}

// ... and soless for rest of list method

THIS WAY THE DOMAIN CLASS KNOWS NOTHING ABOUT How The Mapper Class Does The Lazy Load. Indeed The Domain Class Isn't Even Aware That there is a lazy loading.

EXAMPLE: Using a value Holder (Java)

A value holder can be used as a generic Lazy Load. In this case the domain type is aware that something is afoot, since the product field is typed as a value holder. This fact can be hidden from clients of the supplier by the getting method .

Class Suppliervh ...

Private valueholder products;

Public List getProducts () {

Return (List) products.getValue ();

}

.......................... ..

Class ValueHolder ...

Private Object Value;

Private Valueloader Loader;

Public valueHolder (Valueloader Loader) {

This.Loader = loading;

Public Object getValue () {

IF (value == null) value = loadinger.load ();

Return Value;

}

Public interface valueloader {

Object loading ();

}

A Mapper CAN Set Up Up Up Up Up ItemAn The Loader And Putting It Into The Supplier Object

Class SupplierMapper ...

Protected DomainObject Doload (long ID, resultset r) throws sqlexception {

String namearg = rs.getstring (2);

Suppliervh Result = New SupplierVH (ID, NameArg);

Result.SetProducts (New ProductLoader (NEW ProductLoader (ID));

Return Result;

}

Public Static Class ProductLoader IMPLEments VALUELOADER {

Private long id;

Public ProductLoader (long id) {

THIS.ID = ID;

}

Public Object loading () {

Return ProductMapper.create (). FindForsupPlier (ID);

}

}

转载请注明原文地址:https://www.9cbs.com/read-5211.html

New Post(0)