Dejell
Dejell

Reputation: 14317

LazyInitializationException when field is eager

I have class OmQcActivity like this:

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Table(name="OM_QC_ACTIVITY")
public class OmQcActivity{
   @ManyToOne(fetch = FetchType.EAGER)
   @JoinColumn(name="STATUS_ID")
   private Codesc status;
}

codesc is another entity.

In my code I wrote:

OmQcActivity  myactivity = findQCActivityById(5);
Codesc status = myactivity.getCodesc();

@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
    public OmQcActivity findQCActivityById(Long id) {
        return session.load(persistentClass, id);
    }

however, I get:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:86)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:140)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
    at com.mycompany.model.OmQcActivity_$$_javassist_11.getStatus(OmQcActivity_$$_javassist_11.java)

how can I get Lazy exception if the fetch type is eager?

Upvotes: 2

Views: 2605

Answers (2)

axtavt
axtavt

Reputation: 242686

load() doesn't load an entity immediately, it returns a lazy proxy that fetches the real data at the first method call. In most cases you need to use get() instead of load().

Upvotes: 4

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43098

Found this link. If you have CollectionOfElements annotation in your Codesc entity, then the exception about lazy initialization will be raised.

Upvotes: 0

Related Questions