How to configure Spring boot for work with two databases?

后端 未结 2 1005
旧巷少年郎
旧巷少年郎 2021-02-05 17:14

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

2条回答
  •  一个人的身影
    2021-02-05 17:45

    *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.

提交回复
热议问题