How to configure Spring boot for work with two databases?

后端 未结 2 1004
旧巷少年郎
旧巷少年郎 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.

    0 讨论(0)
  • 2021-02-05 17:48

    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:

    • Fetch the data from each catalog, then manipulate in application code. The framework probably has no hooks for doing anything to both servers at the same time.
    • Use MariaDB and its FEDERATEDX Engine.
    0 讨论(0)
提交回复
热议问题