Mauro Monti
Mauro Monti

Reputation: 1088

Spring-Cloud, Hystrix and JPA - LazyInitializationException

I have the following problem trying to integrate Hystrix into an existent Spring Boot application. I am using boot with spring data (jpa repositories). The structure of the app is pretty simple, we have Resources -> Services -> Repositories.

I enabled Hystrix support and annotated one of the service methods that returns an entity as follow:

@HystrixCommand(fallback="getDealsFallback")
public Page<Deal> getDeals(...) {
  // Get the deals from the Index Server.
  return indexServerRepository.findDealsBy(...);
}

public Page<Deal> getDealsFallback(...) {
  // If IndexServer is down, query the DB.
  return dealsRepository.findDealsBy(...);
}

So this works as expected, the real problem resides actually when I return the Entity to the client. I am using OpenEntityManagerInViewFilter so I can serialize my model with its relations. When I use @HystrixCommand in my service method, I get a LazyInitializatioException when It tries to serialize.

I know the cause (or at least I suspect what is the problem), and is because Hystrix is executing in another thread so is not part of the transaction. Changing the Hystrix isolation strategy from THREAD to SEMAPHORE, works correctly since its the same thread, but I understand that is not the correct way to approach the problem.

So my question is, How can I make the Hystrix executing thread be part of the transaction. Is there any workaround that I can apply?

Thanks!

Upvotes: 4

Views: 1243

Answers (1)

Mavlarn
Mavlarn

Reputation: 3883

It is a little old thread, but maybe someone meets this problems too. There is an issue in github about this.

The reason is, hystrix will run in separate thread, which is different from where the previous transaction is. So the transaction and serialization for lazy will not work.

And the 'THREAD' is the recommended execution strategy too. So if you want to use both hystrix and transaction, you should use them in 2 level calls. Like, in first level service function, use transaction, and in second level service function, use hystrix and call first level transactional function.

Upvotes: 1

Related Questions