在spring data mongo DB中更新复合索引文档

时间:2018-02-06 20:40:45

标签: java spring mongodb spring-data

我有一个mongo db集合,它的2个字段设置了复合索引,如下所示

@Document(collection = “customer”)
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@CompoundIndexes({ @CompoundIndex(name = idx1,unique=true ,def = “{‘customerId’ : 1, ‘managerId’: 1}") })
public class CustomerInfo implements Serializable{
private static final long serialVersionUID = -4743404231218445458L;
    private String customerName;
    private Long customerId;
    private Long managerId;
    private Date lastUpdatedTs;
}

现在,当我尝试使用MongoRepository.save()方法更新集合时,我得到以下异常

Caused by: org.springframework.dao.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error collection: customerDB.customer index: idx1 dup key: { : 4790, : 17 }'; nested exception is com.mongodb.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error collection: customerDB.customer index: idx1 dup key: { : 4790, : 17 }'
    at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:73) ~[spring-data-mongodb-1.10.9.RELEASE.jar:na]
    at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2146) ~[spring-data-mongodb-1.10.9.RELEASE.jar:na]
    at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:484) ~[spring-data-mongodb-1.10.9.RELEASE.jar:na]
    at org.springframework.data.mongodb.core.MongoTemplate.insertDBObject(MongoTemplate.java:1049) ~[spring-data-mongodb-1.10.9.RELEASE.jar:na]
    at org.springframework.data.mongodb.core.MongoTemplate.doInsert(MongoTemplate.java:858) ~[spring-data-mongodb-1.10.9.RELEASE.jar:na]
    at org.springframework.data.mongodb.core.MongoTemplate.insert(MongoTemplate.java:799) ~[spring-data-mongodb-1.10.9.RELEASE.jar:na]
    at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.save(SimpleMongoRepository.java:80) ~[spring-data-mongodb-1.10.9.RELEASE.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_151]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_151]

我知道问题是因为MongoRepository.save()方法依赖于entityInformation.isNew()来识别它是一个保存还是更新用例。对我而言,它必须依赖于唯一性复合索引,以确定它是否是更新。对我来说复合索引是mongo集合的主键。任何想法将不胜感激!!

0 个答案:

没有答案