0

I have a function that simply gets a location by id:

public Location getLocationById(Long idSearchedLocation){
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    Location location = null;           
    try{            
        location = (Location) session.load(Location.class, idSearchedLocation);
        //System.out.println(location.getLat() + " " +this.getClass().getName());       

    } catch (HibernateException e) {
        e.printStackTrace();
        session.getTransaction().rollback();
    }catch(Exception e){
        e.printStackTrace();
    }       
    session.getTransaction().commit();      
    return location;
}

In another function I get the location object and I try to access the location fields:

Location location = mainManager.getLocationById(idSearchedLocation);
System.out.println(location.getLat() + " " +this.getClass().getName());

And then I get the exception after I receive the returned location, when I try to print location.getLat():

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

It is weird why I get this error because the Location object does neighter have collections nor associated entities: just String and Float types.

If I uncomment the line that prints location.getLat() in the dao function, all is working as expected, it loads everything (no exception, and the print succeeds). But why is Hibernate not loading the fields of the object in the first case?

UPDATE

@Entity
@Table(name="location")
public class Location {
    private Long id;
    private String name;
    private String country;
    private String address;
    private Float lat;
    private Float lng;
    //getters and setters
}
bogdan.herti
  • 1,110
  • 2
  • 9
  • 18
  • Post your location object please. – Ean V Oct 13 '13 at 05:33
  • Hibernate loads the primitive types by default unless you mark them as lazy. Look at your getters to see if you've marked them as lazy. This can be done for primitives using @Basic annotation. – Ean V Oct 13 '13 at 23:11

1 Answers1

0

Hibernate.initialize(location) was the solution.

It seems that Hibernate lazy loads not only the collections but every object (called proxy).

bogdan.herti
  • 1,110
  • 2
  • 9
  • 18