I am using Spring Boot 2.X with Hibernate 5 to connect two different MySQL databases (Bar and Foo) on different servers. I am trying t
*ToMany Collections are lazy by default in Hibernate & JPA. The error is because Jackson is trying to serialize the OneToMany when the entity manager (aka session in hibernate-speak) is closed. Hence, lazy collections cannot be retrieved.
Spring Boot with JPA by default provides an OpenEntityManagerInViewFilter
for the primary EM. This allows for read-only DB access, but, by default only works for the primary EM.
You have 3 options:
1) You can add a join fetch, e.g. How does the FetchMode work in Spring Data JPA
2) You can add a OpenEntityManagerInViewFilter for the non primary entity manager and add it to your context.
Please note that this implies a challenge, for each Bar and Foo instance, your app will go back to the database to retrieve the OneToMany. This is the part that isn't working for Bar, but is for Foo. This implies a scalability problem (called the N + 1 problem by some) as for each foo and bar, you run an additional query, which will get slow for non-trivial amounts of Foos and Bars.
3) An alternative is to make your collection on Bar and Foo eager (see this https://docs.oracle.com/javaee/7/api/javax/persistence/OneToMany.html#fetch-- ) but this needs to be analyzed carefully if scalability is a concern at all for you.
I'd recommend option #1.
Two databases (aka "catalogs") on the same server? Use only one connection. Then reference thus:
Foo.table1
Bar.table2
Use that syntax wherever you would have a simple table name.
Different servers
It gets messy if the data is not in the same machine. A couple of ideas:
FEDERATEDX
Engine.