Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data : relationships between 2 different data sources

In a Spring Boot Application project, I have 2 data sources:

  • a MySQL database (aka "db1")
  • a MongoDB database (aka "db2")

I'm using Spring Data JPA and Spring Data MongoDB, and it's working great... one at a time.

Saying db1 handles "Players", and db2 handles "Teams" (with a list of players' ID). Is it possible to make the relationship between those 2 heterogeneous entities working? (i.e. @ManyToOne, @Transactional, Lazy/Eager, etc.)

For example, I want to be able to write:

List<Player> fooPlayers = teamDao.findOneById(foo).getPlayers();

EDIT: If possible, I'd like to find a solution working with any spring data project

like image 435
Nicolas Avatar asked Jun 02 '16 12:06

Nicolas


People also ask

Can we connect to 2 different database from spring boot?

Multiple Databases in Spring BootSpring Boot can simplify the configuration above. Now we have defined the data source properties inside persistence-multiple-db-boot. properties according to the Boot autoconfiguration convention.

What is difference between JpaRepository and CrudRepository?

CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.


1 Answers

Unfortunately your conundrum has no solution in spring data.

what may be a possibility is that you create an interface (DAO) class of your own. That DAO class would have implementations to to query both of your DBs. A very crude and short example would be

your DAO
{
    yourFind (id)
    {
        this would find in db2 and return a relevant list of objects
        findOneByID(id)
        get the player from the above retrieved list and query db1
        getPlayer(player)
    }
}

i hope this points you in the right direction

like image 89
Newton Avatar answered Nov 15 '22 22:11

Newton