Manual re-indexing with Spring Repositories

I am having an issue whenever I try to manually re-index my data. Currently all interaction is done through a JPA repository, and so when ever we save an object it is reflected in the index as intended. We want to add in manual re-indexing as we use an external ES cluster, and if that ever becomes unavailable we want to be able to re-index only the most recent objects, instead of the 5+ years of data we have.

We get the objects by calling variations of the JPA repository methods, and some custom methods (findById, findCreatedBetween etc).

To get the full text entity manager we are calling on an EntityManager instance. We have tried autowiring an EntityManagerFactory to create new EntityManager, and we have tried using the @PersistenceContext annotation within a repository which we then extend from our object repository. Both times when we call fullTextEntityManager.index(object) we get a TransientObjectException “The instance was not associated with this session”.

I appreciate this is a spring specific issue, but if anyone has an idea as to how we can get the correct session/entity manager it would be greatly appreciated, as I am pulling my hair out trying to solve this one!

When you use Spring’s injected entity manager, it’s not the actual entity manager, it’s a proxy. What it does under the hood is it creates a new entity manager for every thread and transaction, and delegates to it.

In short, you have to take care to:

  • Call Search.getFullTextEntityManager after you started your transaction, when the actual entity manager has been created by Spring.
  • Always trigger reindexing in the same transaction that loaded the object.
  • Always trigger reindexing in the same thread that loaded the object.

From what I can see in the comments of this StackOverflow question, it seems you solved your problem and it was indeed related to mixing entities from different transactions.

Hi @yrodiere, thanks for the help, it was indeed the incorrect usage of transactions that was causing the error, silly mistake on my part!

1 Like