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

Sau*_*mar 6 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;
}
Run Code Online (Sandbox Code Playgroud)

当我保存时,mongoTemplate.save(object);我只看到在DB而不是6中创建的2个对象.就在保存我的调试行以保存对象之前.

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]]
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?我觉得索引独特的东西不能以某种方式工作.我想要codebrand成为unique combination.

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

    private static final long serialVersionUID = 1L;

    @Id
    private ID id;
}
Run Code Online (Sandbox Code Playgroud)

war*_*gre 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

为了防止这种情况,您需要:

Catalog cat=new Catalog();
ID id=new ID(realUniqueId);  // RealuniqueId can be code+brand for instance
cat.setId(id); 
...
Run Code Online (Sandbox Code Playgroud)