Prevent duplicate save using MongoRepository

1.2k views Asked by At

I have a service to perform CRUD operation in mongo. I am using MongoRepository for this. I problem i am having is when i am inserting duplicate entries i am unable to get any errors back.

@Document(collection = "test")
public class MongoInsert {

@Id
private String identifier;

private String value;

@PersistenceConstructor
public MongoInsert(String identifier, String value) {
    this.identifier = identifier;
    this.value = value;
}

}

I wrote a test which tries to insert the same object twice, the test passes, i am expecting the second insert to thrown an exception.

My mongoTemplate defination is

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="myMongoDbFactory"/>
    <constructor-arg name="mongoConverter" ref="myMappingConverter"/>
    <property name="writeResultChecking" value="EXCEPTION"/>
</bean>

i have tried with 'writeConcern' set to 'ACKNOWLEDGED', but then i was getting erros

Caused by: org.springframework.data.mongodb.UncategorizedMongoDbException: { "serverUsed" : "127.0.0.1:27017" , "ok" : 0 , "code" : 2 , "errmsg" : "cannot use non-majority 'w' mode ACKNOWLEDGED when a host is not a member of a replica set"}; nested exception is com.mongodb.CommandFailureException: { "serverUsed" : "127.0.0.1:27017" , "ok" : 0 , "code" : 2 , "errmsg" : "cannot use non-majority 'w' mode ACKNOWLEDGED when a host is not a member of a replica set"}

What am i missing here?

1

There are 1 answers

0
СанЁк Баглай On BEST ANSWER

Try to use instead of

<property name="writeConcern" value="ACKNOWLEDGED"/>

this one

<property name="writeConcern">
    <value type="com.mongodb.WriteConcern">ACKNOWLEDGED</value>
</property>

(for detail: How assign bean's property an Enum value in Spring config file?)