-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: LazyInitializationException on FetchType.EAGER
PostPosted: Thu Jan 10, 2013 7:18 am 
Newbie

Joined: Tue Sep 04, 2012 8:37 am
Posts: 3
Got many links on discussions of LIE for LAZY loading configurations but none explains the LIE for EAGER fetch configuration. My setup:

Hibernate config:
Code:
<hibernate-configuration>
   <session-factory>
      <property name="connection.pool_size">1</property>
      <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
      <property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
      <property name="hibernate.max_fetch_depth">10</property>
      <property name="hibernate.default_batch_fetch_size">16</property>
      <property name="hibernate.jdbc.batch_size">30</property>
      <property name="hibernate.jdbc.batch_versioned_data">true</property>
      <property name="hibernate.jdbc.use_streams_for_binary">false</property>
      <property name="hibernate.connection.release_mode">after_transaction</property>
      <property name="hibernate.transaction.auto_close_session">true</property>
      <property name="hibernate.transaction.flush_before_completion">true</property>
      <property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
      <property name="hibernate.cache.use_second_level_cache">false</property>
      <property name="hibernate.show_sql">true</property>
   </session-factory>
</hibernate-configuration>


SessionFactory provider:
Code:
public class HibernateUtil {

   private static final SessionFactory sessionFactory;
   
   static {
      try {
         Configuration conf = new Configuration().
            configure();
         Class[] mappedClasses = getMappedClasses("com.company.projectname.domain");
         for (Class cls: mappedClasses) {
            conf.addAnnotatedClass(cls);
         }
         sessionFactory =
            conf.
            buildSessionFactory();
      } catch (Throwable ex) {
         ex.printStackTrace(System.err);
         throw new ExceptionInInitializerError(ex);
      }
   }
   
   public static SessionFactory getSessionFactory() {
      return sessionFactory;
   }
}


Entity class:
Code:
@Entity
@Table(name="users")
//@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class User implements IsSerializable {

   private Long id;
   private String login;
   private String name;
   private String email;
   private String password;

   //@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
   @ManyToMany(fetch = FetchType.EAGER, targetEntity = Role.class)
   @JoinTable(
      name = "users_roles",
      joinColumns = {@JoinColumn(name = "user_id")},
      inverseJoinColumns = {@JoinColumn(name = "role_id")}
   )
   private Set<Role> roles;
   
   public User() {}

   public User(User user) {
      this.id = user.getId();
      this.login = user.getLogin();
      this.name = user.getName();
      this.email = user.getEmail();
      this.password = user.getPassword();
      this.roles = user.getRoles();
   }
   
   @Id
   @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="users_id_seq")
   @SequenceGenerator(name="users_id_seq", allocationSize=1, sequenceName="users_id_seq")
   @NotNull
   public Long getId() {
      return id;
   }

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

   @NotNull
   public String getLogin() {
      return login;
   }

   public void setLogin(String login) {
      this.login = login;
   }

   @NotNull
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   @NotNull
   public String getEmail() {
      return email;
   }

   public void setEmail(String email) {
      this.email = email;
   }

   @NotNull
   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

   @ManyToMany(fetch = FetchType.EAGER, targetEntity = Role.class)
   @JoinTable(
      name = "users_roles",
      joinColumns = {@JoinColumn(name = "user_id")},
      inverseJoinColumns = {@JoinColumn(name = "role_id")}
   )
   public Set<Role> getRoles() {
      return roles;
   }
   
   @Transient
   public String getRolesNames() {
      String[] names = null;
      if (roles instanceof Set) {
         names = new String[roles.size()];
         int i = 0;
         for (Role role: roles) {
            names[i++] = role.getName();
         }
      }
      if (names == null) return "NONE";
      return names.toString();
   }

   public void setRoles(Set<Role> roles) {
      this.roles = roles;
   }
   
   @Override
   @Transient
   public boolean equals(Object user) {
      if (this == user) return true;
      if (user == null || ! (user instanceof User)) return false;
      User cmp = (User)user;
      if (login == cmp.getLogin()) return true;
      if (login == null) return false;
      return login.equals(cmp.getLogin());
   }
   
   @Override
   @Transient
   public int hashCode() {
      if (login != null) return login.hashCode();
      return super.hashCode();
   }

   @Override
   @Transient
   public String getDescriptiveName() {
      return name + "(" + id + ")";
   }
}


Code, where exception is raised:
Code:
         beginTransaction();
         user = (User) session.
            createCriteria(User.class).
            add(Restrictions.eq("login", action.getLogin())).
            add(Restrictions.eq("password", action.getPassword())).
            uniqueResult();
         session.flush();
         commit();
         if (user instanceof User) {
            doSomethWithEntity(user);
         }


Within doSomethWithEntity there is an iteration step through user.getRoles(). And at that point I get:
Code:
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed
   at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
   at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
   at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368)
   at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:111)
   at org.hibernate.collection.PersistentSet.iterator(PersistentSet.java:186)


Hibernate: 3.6.10.Final, Hibernate-Commons-Annotations: 3.2.0.Final, Hibernate-JPA-2.0-API: 1.0.1.Final, Hibernate-Validator: 4.3.1.Final

Init log:
Code:
66 [btpool0-2] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
71 [btpool0-2] INFO org.hibernate.cfg.Environment - Hibernate 3.6.10.Final
72 [btpool0-2] INFO org.hibernate.cfg.Environment - hibernate.properties not found
74 [btpool0-2] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
76 [btpool0-2] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
114 [btpool0-2] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
114 [btpool0-2] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
148 [btpool0-2] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
185 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.MountCabinet
208 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.MountCabinet on table mountcabinets
264 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.User
265 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.User on table users
270 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.Department
270 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.Department on table departments
271 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.Cable
271 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.Cable on table cables
279 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.Company
279 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.Company on table companies
280 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.Usersetting
280 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.Usersetting on table usersettings
282 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.NetuserEmail
282 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.NetuserEmail on table emails
283 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.Port
283 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.Port on table ports
288 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.DeviceModel
288 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.DeviceModel on table devicemodels
291 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.Netuser
291 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.Netuser on table netusers
295 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.History
296 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.History on table histories
298 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.CableReport
298 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.CableReport on table cablereports
301 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.Device
301 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.Device on table devices
305 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.Room
306 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.Room on table rooms
308 [btpool0-2] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.company.projectname.domain.Role
308 [btpool0-2] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.company.projectname.domain.Role on table roles
314 [btpool0-2] INFO org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: com.company.projectname.domain.Room.cabinets -> mountcabinets
315 [btpool0-2] INFO org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: com.company.projectname.domain.Device.ports -> ports
315 [btpool0-2] INFO org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: com.company.projectname.domain.DeviceModel.devices -> devices
317 [btpool0-2] INFO org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: com.company.projectname.domain.MountCabinet.devices -> devices
320 [btpool0-2] INFO org.hibernate.cfg.Configuration - Hibernate Validator not found: ignoring
14:54:28,450  INFO Version:27 - HV000001: Hibernate Validator 4.3.1.Final
14:54:28,460 DEBUG DefaultTraversableResolver:106 - Found javax.persistence.Persistence on classpath containing 'getPersistenceUtil'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver
14:54:28,462 DEBUG DefaultTraversableResolver:117 - Instantiated JPA aware TraversableResolver of type org.hibernate.validator.internal.engine.resolver.JPATraversableResolver.
14:54:28,465 DEBUG ValidationXmlParser:184 - Trying to load META-INF/validation.xml for XML based Validator configuration.
14:54:28,469 DEBUG ValidationXmlParser:187 - No META-INF/validation.xml found. Using annotation based configuration only.
14:54:28,587 DEBUG DefaultTraversableResolver:106 - Found javax.persistence.Persistence on classpath containing 'getPersistenceUtil'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver
14:54:28,587 DEBUG DefaultTraversableResolver:117 - Instantiated JPA aware TraversableResolver of type org.hibernate.validator.internal.engine.resolver.JPATraversableResolver.
14:54:28,588 DEBUG ValidationXmlParser:184 - Trying to load META-INF/validation.xml for XML based Validator configuration.
14:54:28,588 DEBUG ValidationXmlParser:187 - No META-INF/validation.xml found. Using annotation based configuration only.
486 [btpool0-2] INFO org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
492 [btpool0-2] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
492 [btpool0-2] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 1
492 [btpool0-2] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
498 [btpool0-2] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: org.postgresql.Driver at URL: jdbc:postgresql://host:5432/databasename
498 [btpool0-2] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {useUnicode=true, user=projectdbu, password=****, characterEncoding=utf-8, release_mode=after_transaction}
811 [btpool0-2] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.PostgreSQLDialect
821 [btpool0-2] INFO org.hibernate.engine.jdbc.JdbcSupportLoader - Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
821 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Database ->
       name : PostgreSQL
    version : 9.1.6
      major : 9
      minor : 1
821 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Driver ->
       name : PostgreSQL Native Driver
    version : PostgreSQL 9.0 JDBC4 (build 801)
      major : 9
      minor : 0
822 [btpool0-2] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)
822 [btpool0-2] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
822 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): enabled
822 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: enabled
822 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 30
822 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: enabled
823 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
823 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
823 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: after_transaction
823 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 10
823 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 16
823 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
823 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
823 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
823 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
824 [btpool0-2] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
824 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
824 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled
824 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: disabled
824 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled
824 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
825 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
825 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
827 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout
828 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled
828 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
828 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
828 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
828 [btpool0-2] INFO org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): disabled
841 [btpool0-2] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
845 [btpool0-2] INFO org.hibernate.type.BasicTypeRegistry - Type registration [materialized_blob] overrides previous : org.hibernate.type.MaterializedBlobType@3035228
1366 [btpool0-2] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured


Top
 Profile  
 
 Post subject: Re: LazyInitializationException on FetchType.EAGER
PostPosted: Fri Jan 11, 2013 1:44 am 
Newbie

Joined: Tue Sep 04, 2012 8:37 am
Posts: 3
Could be closed as not a bug. My fault as in doSomethWithEntity(user) I just need to make my object serializable by GWT (no PersistentCollection, just plain java collections). Doing this recursive way I missed a bug in my code and a new instance of User to where cleaned-up and detached from hibernate results were copied I iterated through PersistentSet<Role> roles. My bug was that new instance's 'roles' field were instantiated as PersistentSet too.

PS. I do know of Dozer and Gilead but first requires to create DTOs with no option to use DAO as DTO (my understanding of the docs) and this requirement is an overcomplexity, last is a dead project.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.