I found many times on stackoverflow this issue, but nothing from them gives me clear answer. For simplicity, there are only two tables film and language bound many to one relation. Everything done according Netbeans Hibernate DVD Store tutorial. Now, how to display in first page (index.xhtml) language. It looks like very straightforward. Simply add:
<h:column>
<f:facet name="header">
<h:outputText value="Language"/>
</f:facet>
<h:outputText value="#{item.languageByLanguageId.langName}"/>
</h:column>
(Comumn in table language name was renamed on langName) But it issues still the same LazyInitializationException. I tried to obtain languageId and in this case I was successful. It means #{item.languageByLanguageId.langName} gives exception but #{item.languageByLanguageId.languageId} not. It is strange. So what happen, when I use explicit fetch according languageId if I can obtain its.
So I added in FilmController.java method for obtaining language:
public String getLanguageById(Integer langId) {
String language = helper.getLangById(langId);
return language;
}
And in FilmHelper.java (final version):
public Film getFilmById(int filmId) {
Film film = null;
try {
session = HibernateUtil.getSessionFactory().getCurrentSession();
org.hibernate.Transaction tx = session.beginTransaction();
Query q = session.createQuery("select count(film.filmId) from Film as film where film.filmId = :filmId");
q.setParameter("filmId", filmId);
Number count = (Number) q.uniqueResult();
if (count.intValue() > 0)
film = (Film) session.load(Film.class, filmId);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
}
return film;
}
And yes, it works, I can obtain language name to modify index.xhtml:
<h:outputText value="{filmController.getLanguageById(item.languageByLanguageId.languageId)}"/>
Than I tried to modify FilmActor.hbm.xml to add lazy="false" and use origin simple solution in index.xhtml ("#{item.languageByLanguageId.langName}"):
<many-to-one name="languageByOriginalLanguageId" class="dvdrental.Language" lazy="false" fetch="select">
<column name="original_language_id" />
</many-to-one>
Again it works properly. Even if I set lazy="proxy" or lazy="no proxy". But still I don't understand, how to use this default attribute lazy="true". If I try to keep whole document in one session (don't do commit, which causes end of session), there is another Exception issue. It looks like, that lazy="true" doesn't meet in any time proper result.