1
votes

When I do a Hibernate merge() to a ItemVersionLanguage object, I got "ERROR [org.hibernate.LazyInitializationException] (pool-9-thread-1) could not initialize proxy - no Session: org.hibernate.LazyInitializationException: could not initialize proxy - no Session" from the codes below.

But when I get data from it, it works fine from either ItemVersion or ItemVersionLanguage's url.

I don't have a @Transactional wrapping the code in which merge() locates.

ItemVersionLanguage.java

@Entity
@Table(name = "item_version_language")
public class ItemVersionLanguage implements java.io.Serializable {
   private String url;
   private ItemVersion itemVersion;

   public void setUrl(String url)
   {
      this.url = url;
   } 
   @Column(name = "url")  
   public String getUrl()
   {
      if(this.url == null)
      {
          return this.itemVersion.url; //this results in the problem!
      }
      else
      {
          return this.url;
      }
   }
   public void setItemVersion(ItemVersion itemVersion)
   {
       this.itemVersion = itemVersion;
   }

   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name = "item_version_obj_id", nullable = false)
   public ItemVersion getItemVersion()
   {
       return this.itemVersion;
   }
}

ItemVersion.java

@Entity
@Table(name = "item_version")
public class ItemVersion implements java.io.Serializable {
   private String url;

   public void setUrl(String url)
   {
      this.url = url;
   }   
   @Column(name = "url")
   public String getUrl()
   {
      return this.url;
   }
}

Am I doing anything wrong?

1

1 Answers

1
votes

Lazy initialization enables the variable to act as a proxy which can fetch its value as need be. This error occurs when code attempts to read from the variable after the session that retrieves the entity has been closed, which makes it impossible for the proxy to lazily fetch its value.

You can use Hibernate.initialize(itemVersionLanguage.getItemVersion()) to load the proxy's value before the session is closed.

See http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/performance.html#performance-fetching-initialization for more details.