<p>In Hibernate we have two classes with the following classes with JPA mapping:</p>

<pre><code>package com.example.hibernate

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class Foo {
  private long id;
  private Bar bar;

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  @ManyToOne(fetch = FetchType.LAZY)
  public Bar getBar() {
    return bar;
  }

  public void setBar(Bar bar) {
    this.bar = bar;
  }
}

package com.example.hibernate

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;


public class Bar {
  private long id;
  private String title;

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }


  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  } 
}
</code></pre>

<p>Now when we load from the database an object from class Foo using session get e.g:</p>

<p>Foo foo = (Foo)session.get(Foo.class, 1 /* or some other id that exists in the DB*/);
the Bar member of foo is a proxy object (in our case javassist proxy but it can be cglib one depending on the bytecode provider you use), that is not initialized.
If you then use session.get to fetch the Bar object that is the member of the Foo class just loaded (we are in the same session), Hibernate does not issue another DB query and fetches the object from the session (first level) cache. The problem is this is a proxy to Bar class which is not initialized and trying to call this object getId() will return 0, and getTitle() will return null. 
Our current solution is pretty ugly and checks if the object returned from get is a proxy here is the code (form a generic DAO implementation):</p>

<pre><code>@SuppressWarnings("unchecked")
@Override
@Transactional(readOnly = true)
public &lt;T extends IEntity&gt; T get(Class&lt;T&gt; clazz, Serializable primaryKey) throws DataAccessException {
  T entity = (T) currentSession().get(clazz, primaryKey);
  if (entity != null) {
    if (LOG.isWarnEnabled()) {
      LOG.warn("Object not found for class " + clazz.getName() + " with primary key " + primaryKey);
    }
  } else if (entity instanceof HibernateProxy){ // TODO: force initialization due to Hibernate bug
    HibernateProxy proxy = (HibernateProxy)entity;
    if (!Hibernate.isInitialized(proxy)) {
      Hibernate.initialize(proxy);
    }
    entity = (T)proxy.getHibernateLazyInitializer().getImplementation();
  }
  return entity;
}
</code></pre>

<p>Is there a better way to do this, couldn't find a solution in the Hibernate forum, and didn't find the issue in Hibernate's JIRA.</p>

<p>Note: we cannot just use foo.getBar() (which will initialize the proxy properly) to get the Bar class object, because the session.get operation to fetch the Bar object does not know (or care for that matter) that the Bar class is also a lazy member of a Foo object that was just fetched.</p>

[{'answer_id': 61935, 'author': 'Chris Kimpton', 'author_id': 48310, 'author_profile': 'https://Stackoverflow.com/users/48310', 'pm_score': 0, 'selected': False, 'text': '<p>Not really seen this problem, although we do get intermittent Lazy Load errors - so perhaps we have the same problem, anyway, is it an option to use a different session for the loading of the Bar object - that should load it from scratch, I would expect...</p>\n'}, {'answer_id': 61989, 'author': 'Binil Thomas', 'author_id': 3973, 'author_profile': 'https://Stackoverflow.com/users/3973', 'pm_score': 0, 'selected': False, 'text': '<p>I am unable to reproduce the behaviour you are seeing. Here is my code:</p>\n\n<pre><code>@Entity\npublic class Foo {\n    private Long id; private String name; private Bar bar;\n\n    public Foo() { }\n    public Foo(String name) { this.name = name; }\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    public Long getId() { return id; }\n    public void setId(Long id) { this.id = id; }\n\n    @Basic\n    public String getName() { return name; }\n    public void setName(String name) { this.name = name; }\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    public Bar getBar() { return bar; }\n    public void setBar(Bar bar) { this.bar = bar; }\n}\n\n@Entity\npublic class Bar {\n    private Long id; private String name;\n\n    public Bar() { }\n    public Bar(String name) { this.name = name; }\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    public Long getId() { return id; }\n    public void setId(Long id) { this.id = id; }\n\n    @Basic\n    public String getName() { return name; }\n    public void setName(String name) { this.name = name; }\n}\n\n    public void testGets() {\n        SessionFactory sf = new AnnotationConfiguration()\n            .addPackage("hibtest")\n                .addAnnotatedClass(Foo.class)\n                .addAnnotatedClass(Bar.class)\n            .configure().buildSessionFactory();\n        Session session = null;\n        Transaction txn = null;\n\n        // Create needed data\n        try {\n            session = sf.openSession();\n            txn = session.beginTransaction();\n\n            // Create a Bar\n            Bar bar = new Bar("Test Bar");\n            session.save(bar);\n\n            // Create a Foo\n            Foo foo = new Foo("Test Foo");\n            session.save(foo);\n\n            foo.setBar(bar);\n\n            txn.commit();\n        } catch (HibernateException ex) {\n            if (txn != null) txn.rollback();\n            throw ex;\n        } finally {\n            if (session != null) session.close();\n        }\n\n        // Try the fetch\n        try {\n            session = sf.openSession();\n            Foo foo = (Foo) session.get(Foo.class, 1L);\n            Bar bar = (Bar) session.get(Bar.class, 1L);\n            System.out.println(bar.getName());\n        } finally {\n            if (session != null) session.close();\n        }\n    }\n</code></pre>\n\n<p>And it all works fine, as one would expect.</p>\n'}, {'answer_id': 62246, 'author': 'Darren Greaves', 'author_id': 151, 'author_profile': 'https://Stackoverflow.com/users/151', 'pm_score': 0, 'selected': False, 'text': '<p>Do you actually need to do lazy loading?<br>\nCould you not set FetchType to EAGER instead and have it always loaded (properly) using a join?</p>\n'}, {'answer_id': 120242, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I had a similar problem:</p>\n\n<ul>\n<li>I did Session.save(nastyItem) to save an object into the Session.\nHowever, I did not fill in the property buyer which is mapped as update="false" insert="false" (this happens a lot when you have a composed primary key, then you map the many-to-one\'s as insert="false" update="false")</li>\n<li>I a query to load a list of items, and the item which I just saved, happens to be part of the result set</li>\n<li>now what goes wrong? Hibernate sees that the item was already in the cache, and Hibernate does not replace (probably not to break my earlier reference nastyItem) it with the newly loaded value, but uses MY nastyItem I have put into the Session cache myself. Even worse, now the lazy loading of the buyer is broken: it contains null.</li>\n</ul>\n\n<p>To avoid these Session issues, I always do a flush and a clear after a save, merge, update or delete. Having to solve these nasty problems takes too much of my time.</p>\n'}, {'answer_id': 178835, 'author': 'Miguel Ping', 'author_id': 22992, 'author_profile': 'https://Stackoverflow.com/users/22992', 'pm_score': 0, 'selected': False, 'text': "<p>You are doing something wrong. I did not test your code, but you should never need to force the initialization of proxies, the property accessors do that for you. If you are using Hibernate explicitly, never mind using JPA, since you already have lost portability.</p>\n\n<p>Hibernate should detect automatically whenever it needs to fetch or write to db. If you issue a getProperty() from a proxy, hibernate or any other jpa provider should fetch the correspondent row from the db.</p>\n\n<p>The only situation I'm not sure hibernate is <em>clever</em> enough is if you issue a save() and then issue a get() with the id of the saved object, there might be a problem if the save() didn't flush the object to db.</p>\n"}]
['https://Stackoverflow.com/questions/61906', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3332/']