I have a case where I get LazyInitialzationException in my project. It happens on here:
if (study.getIbId().equals(actor.getRepository().getIbId())) {
actor variable is type of Account and Repository is type of Repository. Ibid is Long type. Account and Repository comes from hibernate. Error is coming from getIbId(), which means Repository object was not hydrated(?). Here is Account.hbm.xml file:
Account:
...
</many-to-one>
<many-to-one cascade="all" class="com.accelarad.data.mapping.account.Repository" column="REPOSITORY_ID" lazy="proxy" name="repository" unique="true">
...
As you can see, there is lazy=proxy property. When I change it to lazy=false, I don't get LazyInitializationException no more.
From what I understand, if lazy=false, it is eagerly fetched, so it is not efficient to do so. Is there way to keep lazy=proxy and load the Repository? What do lazy=${something} and fetch=${something} mean?
EDIT: error log:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:147)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:260)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:73)
at com.accelarad.data.mapping.account.Repository_$$_jvst9a5_5d.getIbId(Repository_$$_jvst9a5_5d.java)
at com.accelarad.smr.widgets.service.impl.ShareImageServiceImpl.isNetworkStudy(ShareImageServiceImpl.java:265)
at com.accelarad.smr.widgets.ShareImageController.autoCompleteAccount(ShareImageController.java:231)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
There are some information missing such as how you are managing the session and transactions. The exception tells you just that, there is no session bound to your request.
Nevertheless I'll try to point you in a good direction. First you will need a SessionFactory object to manage your sessions. It is a good practice to encapsulate it in a Singleton pattern because hibernate sessions are not thread safe.
So now you can call Session hSession = HibernateFactory.getInstance().getSession();
Then make sure your lazy load is inside the transaction bound you define.
Generally you won't need to explicitly open a transaction if you are just fetching data but it's a good practice anyway. If you do, remember to commit and rollback if needed.
Also for your other question on what is fetch and load. Refer to: https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/performance.html