Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lect17-hibernate-orm / more / hibernate_reference.pdf
Скачиваний:
54
Добавлен:
18.03.2015
Размер:
2.2 Mб
Скачать

Initializing collections and proxies

These problems are all due to fundamental limitations in Java's single inheritance model. To avoid these problems your persistent classes must each implement an interface that declares its business methods. You should specify these interfaces in the mapping file where CatImpl implements the interface Cat and DomesticCatImpl implements the interface DomesticCat. For example:

<class name="CatImpl" proxy="Cat">

......

<subclass name="DomesticCatImpl" proxy="DomesticCat">

.....

</subclass> </class>

Then proxies for instances of Cat and DomesticCat can be returned by load() or iterate().

Cat cat = (Cat) session.load(CatImpl.class, catid);

Iterator iter = session.createQuery("from CatImpl as cat where cat.name='fritz'").iterate();

Cat fritz = (Cat) iter.next();

Note

list() does not usually return proxies.

Relationships are also lazily initialized. This means you must declare any properties to be of type

Cat, not CatImpl.

Certain operations do not require proxy initialization:

equals(): if the persistent class does not override equals()

hashCode(): if the persistent class does not override hashCode()

The identifier getter method

Hibernate will detect persistent classes that override equals() or hashCode().

By choosing lazy="no-proxy" instead of the default lazy="proxy", you can avoid problems associated with typecasting. However, buildtime bytecode instrumentation is required, and all operations will result in immediate proxy initialization.

21.1.4. Initializing collections and proxies

A LazyInitializationException will be thrown by Hibernate if an uninitialized collection or proxy is accessed outside of the scope of the Session, i.e., when the entity owning the collection or having the reference to the proxy is in the detached state.

329

Chapter 21. Improving performance

Sometimes a proxy or collection needs to be initialized before closing the Session. You can force initialization by calling cat.getSex() or cat.getKittens().size(), for example. However, this can be confusing to readers of the code and it is not convenient for generic code.

The static methods Hibernate.initialize() and Hibernate.isInitialized(), provide the application with a convenient way of working with lazily initialized collections or proxies.

Hibernate.initialize(cat) will force the initialization of a proxy, cat, as long as its Session is still open. Hibernate.initialize( cat.getKittens() ) has a similar effect for the collection of kittens.

Another option is to keep the Session open until all required collections and proxies have been loaded. In some application architectures, particularly where the code that accesses data using Hibernate, and the code that uses it are in different application layers or different physical processes, it can be a problem to ensure that the Session is open when a collection is initialized. There are two basic ways to deal with this issue:

In a web-based application, a servlet filter can be used to close the Session only at the end of a user request, once the rendering of the view is complete (the Open Session in View pattern). Of course, this places heavy demands on the correctness of the exception handling of your application infrastructure. It is vitally important that the Session is closed and the transaction ended before returning to the user, even when an exception occurs during rendering of the view. See the Hibernate Wiki for examples of this "Open Session in View" pattern.

In an application with a separate business tier, the business logic must "prepare" all collections that the web tier needs before returning. This means that the business tier should load all the data and return all the data already initialized to the presentation/web tier that is required for a particular use case. Usually, the application calls Hibernate.initialize() for each collection that will be needed in the web tier (this call must occur before the session is closed) or retrieves the collection eagerly using a Hibernate query with a FETCH clause or a FetchMode.JOIN in

Criteria. This is usually easier if you adopt the Command pattern instead of a Session Facade.

You can also attach a previously loaded object to a new Session with merge() or lock() before accessing uninitialized collections or other proxies. Hibernate does not, and certainly should not, do this automatically since it would introduce impromptu transaction semantics.

Sometimes you do not want to initialize a large collection, but still need some information about it, like its size, for example, or a subset of the data.

You can use a collection filter to get the size of a collection without initializing it:

( (Integer) s.createFilter( collection, "select count(*)" ).list().get(0) ).intValue()

The createFilter() method is also used to efficiently retrieve subsets of a collection without needing to initialize the whole collection:

330

Using batch fetching

s.createFilter( lazyCollection, "").setFirstResult(0).setMaxResults(10).list();

21.1.5. Using batch fetching

Using batch fetching, Hibernate can load several uninitialized proxies if one proxy is accessed. Batch fetching is an optimization of the lazy select fetching strategy. There are two ways you can configure batch fetching: on the class level and the collection level.

Batch fetching for classes/entities is easier to understand. Consider the following example: at runtime you have 25 Cat instances loaded in a Session, and each Cat has a reference to its owner, a Person. The Person class is mapped with a proxy, lazy="true". If you now iterate through all cats and call getOwner() on each, Hibernate will, by default, execute 25 SELECT statements to retrieve the proxied owners. You can tune this behavior by specifying a batch-size in the mapping of Person:

<class name="Person" batch-size="10">...</class>

Hibernate will now execute only three queries: the pattern is 10, 10, 5.

You can also enable batch fetching of collections. For example, if each Person has a lazy collection of Cats, and 10 persons are currently loaded in the Session, iterating through all persons will generate 10 SELECTs, one for every call to getCats(). If you enable batch fetching for the cats collection in the mapping of Person, Hibernate can pre-fetch collections:

<class name="Person">

<set name="cats" batch-size="3">

...

</set> </class>

With a batch-size of 3, Hibernate will load 3, 3, 3, 1 collections in four SELECTs. Again, the value of the attribute depends on the expected number of uninitialized collections in a particular Session.

Batch fetching of collections is particularly useful if you have a nested tree of items, i.e. the typical bill-of-materials pattern. However, a nested set or a materialized path might be a better option for read-mostly trees.

21.1.6. Using subselect fetching

If one lazy collection or single-valued proxy has to be fetched, Hibernate will load all of them, re-running the original query in a subselect. This works in the same way as batch-fetching but without the piecemeal loading.

331

Chapter 21. Improving performance

21.1.7. Fetch profiles

Another way to affect the fetching strategy for loading associated objects is through something called a fetch profile, which is a named configuration associated with the org.hibernate.SessionFactory but enabled, by name, on the org.hibernate.Session. Once enabled on a org.hibernate.Session, the fetch profile will be in affect for that org.hibernate.Session until it is explicitly disabled.

So what does that mean? Well lets explain that by way of an example which show the different available approaches to configure a fetch profile:

Example 21.1. Specifying a fetch profile using @FetchProfile

@Entity

@FetchProfile(name = "customer-with-orders", fetchOverrides = {

@FetchProfile.FetchOverride(entity = Customer.class, association = "orders", mode = FetchMode.JOIN)

})

public class Customer { @Id

@GeneratedValue private long id;

private String name;

private long customerNumber;

@OneToMany

private Set<Order> orders;

// standard getter/setter

...

}

Example 21.2. Specifying a fetch profile using <fetch-profile> outside <class>

node

<hibernate-mapping>

<class name="Customer">

...

<set name="orders" inverse="true"> <key column="cust_id"/> <one-to-many class="Order"/>

</set> </class>

<class name="Order">

...

</class>

<fetch-profile name="customer-with-orders">

<fetch entity="Customer" association="orders" style="join"/> </fetch-profile>

332

Fetch profiles

</hibernate-mapping>

Example 21.3. Specifying a fetch profile using <fetch-profile> inside <class>

node

<hibernate-mapping>

<class name="Customer">

...

<set name="orders" inverse="true"> <key column="cust_id"/> <one-to-many class="Order"/>

</set>

<fetch-profile name="customer-with-orders"> <fetch association="orders" style="join"/>

</fetch-profile> </class>

<class name="Order">

...

</class> </hibernate-mapping>

Now normally when you get a reference to a particular customer, that customer's set of orders will be lazy meaning we will not yet have loaded those orders from the database. Normally this is a good thing. Now lets say that you have a certain use case where it is more efficient to load the customer and their orders together. One way certainly is to use "dynamic fetching" strategies via an HQL or criteria queries. But another option is to use a fetch profile to achieve that. The following code will load both the customer andtheir orders:

Example 21.4. Activating a fetch profile for a given Session

Session session = ...;

session.enableFetchProfile( "customer-with-orders" ); // name matches from mapping

Customer customer = (Customer) session.get( Customer.class, customerId );

Note

@FetchProfile definitions are global and it does not matter on which class you place them. You can place the @FetchProfile annotation either onto a class or package (package-info.java). In order to define multiple fetch profiles for the same class or package @FetchProfiles can be used.

Currently only join style styles. See HHH-3414 for details.

fetch profiles are supported, but they plan is to support additional [http://opensource.atlassian.com/projects/hibernate/browse/HHH-3414]

333

Соседние файлы в папке more