1

below is my hibernate code:

SessionFactory sessionFactory;
        Session session = null;
        LoginEntity user = null;

        try {

            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            session.beginTransaction();

            user = session.get(LoginEntity.class, user_id);

            System.out.println(user.getUserCountryMapping()); // if I remove this line I get error..

            session.getTransaction().commit();
            return user;

        } catch (Exception e) {
            Logger.getLogger(BulkActionMethods.class.getName()).log(Level.SEVERE, null, e);
        } finally {
            if (session != null) {
                session.close();
            }
        }

I am facing a weird issue with my code, When I remove the System.out.println(user.getUserCountryMapping()); line I am getting HTTP Status 500 - Internal Server Error error on browser but when I write this line I am getting expacted JSON response on browser.. Please someone help me to understand this issue.

ansh
  • 573
  • 3
  • 9
  • 26

2 Answers2

3

Without seeing the error or your entity mappings, it's hard to give a firm answer.

However, cases like this are almost always due to uninitialized lazy collections. The line:

System.out.println(user.getUserCountryMapping()); 

makes Hibernate fetch the data in that relationship. If you don't do this within a Hibernate session, and then try to rely on this relationship later you will get a LazyInitializationException, if not handled it will be a HTTP status 500.

StuPointerException
  • 7,117
  • 5
  • 29
  • 54
1

Replace

System.out.println(user.getUserCountryMapping());

with

Hibernate.initialize(user.getUserCountryMapping());

Read more about lazy vs eager fetch type.

Kartik
  • 7,677
  • 4
  • 28
  • 50