We have used the default fetch strategy in the preceding example. The default fetch strategy for OneToMany
and ManyToMany
relationships is LAZY
. With LAZY
fetching, the containing entities are not fetched when the contained entity is retrieved. Therefore, we were not able to retrieve all the editions for a catalog, all the sections in an edition, and all the articles in a section. We just listed all the catalogs, editions, sections, and articles. With EAGER
fetching, the entities contained by an entity are immediately fetched. Next, we shall modify the fetch strategy to EAGER
in the @ManyToMany
and @OneToMany
relationship mappings. The fetch strategy is set with the fetch
element. In the Catalog
entity replace:
@ManyToMany(cascade=CascadeType.ALL)
with:
@ManyToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
In the Edition
entity replace:
@ManyToMany(cascade = { CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }, mappedBy = "editions")
with:
@ManyToMany...