-1

I am using a Model File namely Document.java and Document.hbm.xml from a jar file .

This document class has an object:

class Document{

private Signature signature;

// other fields
// getter setters 

}

with hbm mapping as follows:

<many-to-one name="signature" column="SIGNATURE_ID" class="com.model.Signature"/>

Now as I am accessing these files from jar so I prefer not to change them .

I am taking out the Document object as follows:

Query qry = getSessionFactory().getCurrentSession().createQuery("from
Document where id = :id");
qry.setParameter("id" , id);
return (Document)qry.list().get(0);

But now when I take out a Signature object through following code:

I have a utility class Utils.java so I am accessing it as :

Utils utils = new Utils();

utils.getSignatures(document);

and this getSignatures method inside Utils class is

public Signatures getSignatures (Document document){

Signature sign = document.getSignature();

// working on sign object

return sign;
}

So now as in above code when ever I do document.getSignature() I get the following error:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

Cœur
  • 32,421
  • 21
  • 173
  • 232
Tarun
  • 251
  • 1
  • 4
  • 16

2 Answers2

0

You should either get your signatures while you have an open session like:

Document document = session.get(whatEverID);
Signature signature = document.getSignature();

Or eagerly fetch your signatures like:

<many-to-one name="signature" column="SIGNATURE_ID" class="com.model.Signature" fetch="eager"/>

Or join fetch your signatures like:

Criteria criteria = createCriteria().setFetchMode("signature", FetchMode.JOIN);

I don't know which version of hibernate(or other JPA implementation) you are using so codes that i have provided could vary.

selman
  • 975
  • 1
  • 12
  • 26
0

Lazy loading requires a transaction. Basically, your typical workflow with Hibernate transactions should be like this:

Session session = null;
Transaction tx = null;

try {
    session = getSessionFactory().getCurrentSession();
    tx = session.beginTransaction();

    // doSomething(session);

    tx.commit();
} catch(RuntimeException e) {
    try {
        tx.rollback();
    } catch(RuntimeException rollbackException) {
        log.error("Couldn’t roll back transaction", rollbackException);
    }
    throw e;
} finally {
    if(session!=null) {
        session.close();
    }
}

Also read this post about fetching types in the Hibernate.

For more info about lazy loading reference this question.

Vlad Mihalcea
  • 103,297
  • 39
  • 432
  • 788
ledniov
  • 1,888
  • 1
  • 17
  • 24