Own EntityManagerProvider

Probably continuation of the topic Provide my own EntityManagerProvider?

I have got also multiple data sources and axon for dedicated one. I use Spring Boot with axon framework.
My question is how to properly connect bean of LocalContainerEntityManagerFactoryBean with Entity Manager Provider - how to properly instantiate it?

I have sth like below but it doesn’t work:

@Bean(name = "axonEntityManagerProvider")
public EntityManagerProvider axonEntityManagerProvider(
    @Qualifier("axonEntityManagerFactory") EntityManagerFactory entityManagerFactory
) {
    return () -> entityManagerFactory.createEntityManager();
}

where:

@Bean(name = "axonEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory( ...

Could you please advice ?

Hi @jj36, and welcome to the forum!

First and foremost, are you certain you want to construct a new EntityManager instance every time the EntityManagerProvider is invoked? I think you should be able to come by with constructing a single EntityManager instance for a given database and provide that to the SimpleEntityManagerProvider.

Other than that, there’s nothing wrong with the instantiation approach.
But, I guess what you are after is if provisioning the EntityManagerProvider like above is sufficient.

That task at hand for you is to make an EntityManagerProvider for the Axon components only (as it’s a requirement for Axon’s JPA infra components).
The deviation in data source lies between the Event Store and the rest.

Thus, you would set an EntityManagerProvider, using an EntityManager attached to that datas ource.
From there, it is your job to set the EntityManagerProvider on the JpaEventStorageEngine.

For the other Axon tables, you would use the other data source → EntityManagerEntityManagerProvider.
And, subsequently, set that on the Axon-infra components that you use.
For example, on the JpaTokenStore and the JpaSagaStore.

If you want to split the tables over distinct data sources further, you’d simply need to further those steps.

Perhaps the key to what you’re missing is that Axon’s Spring Boot autoconfiguration only deals with a single EntityManagerProvider out of the box.
If you want to use several, you need to set the EntityManagerProvider on Axon’s components manually, and expose those infra-components to the Application Context yourself.

I hope this helps!