2017-08-07 79 views
6

我有類似的模型以下春MongoDB的模板保存在同一個對象

@CompoundIndexes(value = { 
     @CompoundIndex(name = "catalog_idx", def = "{'code' : 1, 'brand' : 1}", unique = true) }) 
@Document(collection = Catalog.ENTITY) 
public class Catalog extends AbstractModel<String> { 

    private static final long serialVersionUID = 1L; 

    public static final String ENTITY = "catalog"; 

    @NotNull(message = "Code is required") 
    @Field("code") 
    private String code; 

    @NotNull(message = "Brand is required") 
    @DBRef(lazy = true) 
    @Field("brand") 
    private Brand brand; 
} 

當我與mongoTemplate.save(object);救我只看到2 DB,而不是6只創建之前保存的對象我調試行對象被保存。

Catalog [code=StagedCatalog, brand=Brand [code=Brand_3]] 
Catalog [code=StagedCatalog, brand=Brand [code=Brand_2]] 
Catalog [code=StagedCatalog, brand=Brand [code=Brand_1]] 
Catalog [code=OnlineCatalog, brand=Brand [code=Brand_2]] 
Catalog [code=OnlineCatalog, brand=Brand [code=Brand_1]] 
Catalog [code=OnlineCatalog, brand=Brand [code=Brand_3]] 

任何想法爲什麼?我覺得索引獨特的東西不能以某種方式工作。我想要codebrandunique combination

public abstract class AbstractModel<ID extends Serializable> implements Serializable { 

    private static final long serialVersionUID = 1L; 

    @Id 
    private ID id; 
} 
+0

你有創建目錄的代碼?你有抽象模型中的「@id」列嗎?你可以記錄嗎? – wargre

+0

@wargre did .... –

回答

5

您已設置唯一索引。這意味着您將無法使用相同的代碼和品牌生成2份文檔。

現在您已將ID列設置爲ID對象。你有2個刀片,而不是6,這意味着你用相同的ID爲3插入,像:

for (code: {"StagedCatalog","OnlineCatalog"}) { 
    ID id=new ID(...); 
    for (brand: {1, 2, 3}){ 
     Catalog cat=new Catalog(); 
     cat.setId(id);    // <<== this is wrong, you reuse the same id, you will insert first brand, then update to brand2 and brand3. 
     cat.setCode(code); 
     cat.setBrand(brand); 
     mongoTemplate.persist(cat); 
    } 
} 

爲了防止這種情況,你需要:

Catalog cat=new Catalog(); 
ID id=new ID(realUniqueId); // RealuniqueId can be code+brand for instance 
cat.setId(id); 
... 
+0

ID由spring mongodb直接設置。 –

+0

你確定你不重用相同的對象? – wargre

+0

是的,我確定。在我保存之前,你會看到日誌。現在沒有任何代碼和品牌組合相互衝突。我從複合鍵的理解,根據春季文檔我希望我的配置是正確的另外,當我做保存所有這些對象都是新鮮的,這意味着在保存之前ID是空值,保存後它們將有一個值。所以我不明白爲什麼春天mongodb節省現有的實體。所以春天mongodb複合鑰匙獨特我認爲組合是獨特的,而不是個別的代碼和品牌是獨特的。 –

相關問題