title: Hibernate Search manual indexing throw a "org.hibernate.TransientObjectException: The instance was not associated with this session"
body: <p>I use Hibernate Search 5.11 on my Spring Boot 2 application, allowing to make full text research.
  This librairy require to index documents.</p>
  
  <p>When my app is launched, I try to re-index manually data of an indexed entity (MyEntity.class) each five minutes (for specific reason, due to my server context).</p>
  
  <p>I try to index data of the MyEntity.class.</p>
  
  <p>MyEntity.class has a property attachedFiles, which is an hashset, filled with a join @OneToMany(), with lazy loading mode enabled :</p>
  
  <pre><code>@OneToMany(mappedBy = "myEntity", cascade = CascadeType.ALL, orphanRemoval = true)
  private Set&lt;AttachedFile&gt; attachedFiles = new HashSet&lt;&gt;();
  </code></pre>
  
  <p>I code the required indexing process, but an exception is thrown on "<em>fullTextSession.index(result);</em>" when attachedFiles property of a given entity is filled with one or more items :</p>
  
  <pre><code>org.hibernate.TransientObjectException: The instance was not associated with this session
  </code></pre>
  
  <p>The debug mode indicates a message like "Unable to load [...]" on entity hashset value in this case.</p>
  
  <p>And if the HashSet is empty (not null, only empty), no exception is thrown.</p>
  
  <p>My indexing method :</p>
  
  <pre><code>private void indexDocumentsByEntityIds(List&lt;Long&gt; ids) {
  
  final int BATCH_SIZE = 128;
  
  Session session = entityManager.unwrap(Session.class);
  
  FullTextSession fullTextSession = Search.getFullTextSession(session);
  fullTextSession.setFlushMode(FlushMode.MANUAL);
  fullTextSession.setCacheMode(CacheMode.IGNORE);
  
  CriteriaBuilder builder = session.getCriteriaBuilder();
  CriteriaQuery&lt;MyEntity&gt; criteria = builder.createQuery(MyEntity.class);
  Root&lt;MyEntity&gt; root = criteria.from(MyEntity.class);
  criteria.select(root).where(root.get("id").in(ids));
  
  TypedQuery&lt;MyEntity&gt; query = fullTextSession.createQuery(criteria);
  
  List&lt;MyEntity&gt; results = query.getResultList();
  
  int index = 0;
  
  for (MyEntity result : results) {
      index++;
      try {
          fullTextSession.index(result); //index each element
          if (index % BATCH_SIZE == 0 || index == ids.size()) {
              fullTextSession.flushToIndexes(); //apply changes to indexes
              fullTextSession.clear(); //free memory since the queue is processed
          }
      } catch (TransientObjectException toEx) {
          LOGGER.info(toEx.getMessage());
          throw toEx;
      }
  }
  }
  </code></pre>
  
  <p>Does someone have an idea ?</p>
  
  <p>Thanks !</p>