Spring mongodb模板保存在同一个对象中

时间:2017-08-07 08:33:08

标签: spring-data spring-mongo spring-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);保存时,我只看到在DB中创建的2个对象而不是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;
}

2 个答案:

答案 0 :(得分:5)

您已设置唯一索引。这意味着您将无法拥有2个具有相同代码和品牌的文档。

现在您已将ID列设置为ID对象。你有2个插入而不是6的事实意味着你对3个插入使用相同的ID,如:

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); 
...

答案 1 :(得分:0)

db.collection.save()

根据文档参数更新现有文档或插入新文档。

Document Structure