Spring Data - MongoDB: Unable to retrieve DBRef document that belongs to another database

我的梦境 提交于 2019-12-24 08:33:15

问题


I have a Entity Market(market is stored in a collection within marketDb database) that references Product (stored in a collection product in productDb database ).

/*Entity */
class Market {

@DBRef (db = "productDb")
private Product product;

}

/**Market is stored in the collection as: */

{
  "_id": "4f0bc0e6-b6a8-11e6-a04d-080027e9004f",
  "_class": "com.package.Market",
  "createdById": "123",
  "editedById": "123",
  "name": "Market01", 
  "clientId": NumberLong("1"),
  "version": NumberLong("1"),
  "product": DBRef("product", "456", "productDb", { "$db": "productDb" })
}

When I try to read the Market by its Id, I am able to fetch the Market but Product returns as null.

However: 1. If the product is stored in a collection that belongs to the same database as Market, then Product is returned as part of read on Market. 2. If in the above code, if I specify the Product reference as: @DBRef (db = "productDb", lazy = true) private Product product;

then I get a reference to the DBRef with the id of the Product entity populated.

Can anyone please suggest why the product entity that belongs to the Market is not being loaded as part of read operation on Market when they belong to different databases? Do I need to add any converter / Custom query to load the referenced product for the Market when the two are in different databases or some add additional configuration for MarketRepository to read the product data from productDb database?

Thanks.

The Mongo-Java Driver that I use is 3.2.2.


回答1:


Hey did you tried with fetch="select" or fetch="join". lazy ="true", it means that it will retrieve the association objects in a separate query, but not at the time of loading the object. fetch="join" it will always fire a single query to get the association objects from the database.



来源:https://stackoverflow.com/questions/40924374/spring-data-mongodb-unable-to-retrieve-dbref-document-that-belongs-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!