2017-06-21 192 views
0

我已經定義以下集合:春數據的MongoDB - 嵌入與@Indexed文檔(唯一= TRUE)

@Document(collection="sectors") 
public class Sector { 

    private final String id = null; 
    @Indexed(unique=true) 
    private String name; 


} 


@Document(collection="companies") 
public class Company { 

    @Id 
    private UUID uid; 
    @Indexed(unique=true) 
    private String nif; 
    private String name; 
    private List<Sector> sectors = new ArrayList<>(); 
} 

如果我嘗試用相同的部門,然後我得到 'E11000 duplicate key error index: fake.companies.sectors.name dup key : {[[sector1, sector2]] }';插入兩家公司

從扇區註釋出@Indexed(unique=true)它的工作原理。爲什麼會這樣?是一個錯誤?我希望部門實體按名稱唯一編制索引,兩個公司在共享相同部門時不應存在任何問題。

+1

這是索引的工作原理。它們在收集文件中是獨一無二的,而不是單個文件。看[解釋](https://docs.mongodb.com/manual/core/index-unique/#unique-constraint-across-separate-documents)和[解決方法](https://jira.mongodb.org/browse/SERVER-1068) – Veeram

+0

@Veeram哦,好吧,那很糟糕。 ty – anat0lius

回答

0

您目前正在創建扇區而不是作爲一個單獨的文檔,而是作爲嵌套的對象。這意味着彈簧數據將忽略@Document註釋並使用註釋@Indexed。沒有一個部門對每個公司都是獨一無二的。

但是,如果您試圖在部門和公司之間建立關係,您應該添加@DBRef以獲得private List<Sector> sectors = new ArrayList<>();

這樣Spring數據將引用扇區。請注意,mongoDB不會爲您級聯,您必須創建該扇區才能將其作爲DBRef參考。另一種方法是保存扇區ID並在需要時手動抓取。

+0

我不想使用@DBRef,因爲我想在查詢時能夠訪問Sector屬性。 – anat0lius