2

I am having a problem converting data to json.

Session session = sessionFactory.openSession();       
Affiliate affiliate = (affiliate) session.get( Affiliate , pk );
session.close();
JSONArray.fromObject(affiliate);

the debugger showing that the row was fetched.
but i get this exception when trying to convert to json string:

Exception in thread "main" net.sf.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.affiliates.hibernate.Affiliate.employees, no session or session was closed
at net.sf.json.JSONObject._fromBean(JSONObject.java:959)    ...

this is my Affiliate Entity

    @Entity(name="AFFILIATE")
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    public class Affiliate extends HibernateBean{ 

        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY) 
        @Column(name="AFFILIATE_ID")
        private long id;

        @ManyToOne(targetEntity = Affiliate.class)
        @JoinColumn(name="PARENT_ID")
        private Affiliate parent;



        @ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
        @JoinTable(name="EMPLOYEES_AFFILIATES"  , joinColumns = {@JoinColumn(name="AFFILIATE_ID")},inverseJoinColumns={@JoinColumn(name="EMPLOYEE_ID")})
        private Set<Employee> employees = new HashSet<Employee>(0);

 getters and setters...

    }

Thanks

2 Answers 2

6

Your employees collection is marked as FetchType.LAZY, therefore it's fetched lazily and can't be fetched when session is closed.

You have several options:

  • If that collection is needed every time you load an Affiliate object, mark it as eagerly fetched:

    @ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER) 
    
  • If you need that collection only in this particular case, instruct Hibernate to load it eagerly in this case:

    • With JOIN FETCH clause:

      Affiliate affiliate = (Affiliate) session.createQuery(
          "from Affiliate a join fetch a.employees where a.id = :id")
          .setParameter("id", pk).uniqueResult()
      
    • With Hibernate.initialize():

      Affiliate affiliate = (Affiliate) session.get( Affiliate , pk );  
      Hibernate.initialize(affiliate.getEmployees());
      
    • With Fetch Profiles

  • Do not close the session before response is ready. Use Open Session in View pattern.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I dont understand one thing, fetch lazy means that emplyees will be null, no? ... because if I am writing affiliate.setEmployees(null), it is working fine. this is what i understand fetch lazy suppose to do, set the emplyees as null.
@fatnjazzy: Lazy fetching means that employees is a proxy collection, that tries to fetch the actual items when you access it.
0

Never change an entity if you are not changing the database. They are supposed to match. Changing the fetch to eager on the entity sabotages the whole idea of lazy loading and there may be other places in your code where you introduce performance problems because of it. This is to say that if you change the entity, then everyone, everywhere MUST load all that data every time they use that entity.

What you want is a nested transaction. Start your transaction at the beginning of the method call that does the JSON conversion and end it at the end of the method. Do this by simply adding a transactional annotation to the method call that contains this JSON conversion.

Having done this, the transaction will not be over with when the information is needed and a lazy load can then take place. Likely there are other places in the code where this is done. Seek them and use them as examples to base your solution off of.

Of course, if you will be using this in a number of places, you may want to actually push it down into your DAO, for re-use.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.