0

我試圖使用RepositoryRestResourceRestTemplate熱切加載的MongoDB @DBRef在Spring數據的RepositoryRestResource

的所有作品,而是很好地實現一個REST API,除了裝載@ DBREF的

考慮這個數據模型:

public class Order 
{ 
    @Id 
    String id; 

    @DBRef 
    Customer customer; 

    ... other stuff 
} 

public class Customer 
{ 
    @Id 
    String id; 

    String name; 

    ... 
} 

和下面的存儲庫(類似一個客戶)

@RepositoryRestResource(excerptProjection = OrderSummary.class) 
public interface OrderRestRepository extends MongoRepositor<Order,String>{} 

的REST API返回以下JSON:

{ 
    "id" : 4, 
    **other stuff**, 
    "_links" : { 
    "self" : { 
     "href" : "http://localhost:12345/api/orders/4" 
    }, 
    "customer" : { 
     "href" : "http://localhost:12345/api/orders/4/customer" 
    } 
    } 
} 

其若被resttemplate將創造客戶新訂購的實例= NULL正確加載

是否有可能急切地解決客戶對信息庫結束並嵌入JSON?

回答

2

在這種情況下急切解決依賴實體將最有可能提高N+1 database access problem。 我不認爲有一種方法可以使用默認的Spring Data REST/Mongo存儲庫實現。

這裏有一些選擇:

  1. 建設,將訪問數據庫和構建所需的輸出
  2. 使用Projections來填充關聯集,例如場的自定義@RestController方法

    @Projection(name = "main", types = Order.class) 
    public interface OrderProjection { 
        ... 
    
        // either 
        @Value("#{customerRepository.findById(target.customerId)}") 
        Customer getCustomer(); 
    
        // or 
        @Value("#{customerService.getById(target.customerId)}") 
        Customer getCustomer(); 
    
        // or 
        CustomerProjection getCustomer(); 
    } 
    
    @Projection(name = "main", types = Customer.class) 
    public interface CustomerProjection { 
        ... 
    } 
    
  3. 的customerService.getById可以採用緩存(例如,使用彈簧@Cachable annotation)以減輕另外訪問數據庫的每個的性能損失的結果集的記錄。

  4. 在創建/更新時向您的數據模型添加冗餘並將Customer對象字段的副本存儲在Order集合中。

這樣的問題出現了,在我看來,因爲MongoDB的不支持加入不同的文檔集合很好(其"$lookup" operator有顯著的侷限性相比於常見的SQL連接)。 MongoDB docs also do not recommend使用@DBRef領域,除非加盟不同的服務器上託管的集合:

除非你有一個令人信服的理由使用DBREFS,使用說明書引用來代替。

這裏也有類似的question

+0

我使用嵌套投影來修復它。這像一個魅力。由於我只需要在檢索單個訂單時進行急切的解決,所以查詢量將會很小。謝謝! –