spring data - how to get error messages from mongoRepository.save() -
i'm using mongorepository.save() cannot error information when duplicates prevent insertion. test i'm inserting duplicate username , mongo ignores it. when username unique inserted expected.
see below service class:
package com.onlinedateshow.service; import org.springframework.beans.factory.annotation.autowired; import org.springframework.data.mongodb.core.mongotemplate; import org.springframework.security.crypto.bcrypt.bcryptpasswordencoder; import org.springframework.stereotype.service; import com.mongodb.basicdbobject; import com.onlinedateshow.data.model.user; import com.onlinedateshow.data.repo.user.userrepository; import com.onlinedateshow.model.ui.registerui; import com.onlinedateshow.model.util.registermapper; @service public class registerservice { @autowired private userrepository userrepo; @autowired mongotemplate template; public string adduser(registerui registerdata) { user newuser = registermapper.topersistencebean(registerdata); try{ //does not return error, if duplicates found, silently //ignores query user saveduser = userrepo.save(newuser); //below want don't know how repository //string error = template.getdb().getlasterror().geterrormessage(); //return error; return null; }catch(exception e){ return e.getlocalizedmessage(); } } }
and userrepository interface:
package com.onlinedateshow.data.repo.user; import org.springframework.data.mongodb.repository.mongorepository; import org.springframework.data.repository.pagingandsortingrepository; import com.onlinedateshow.data.model.user; public interface userrepository extends mongorepository<user, string>, pagingandsortingrepository<user, string> { user findbyemail(string email); user findbyid(string id); user findbyusername(string username); }
and xml file sets mongodbfactory:
<!-- activate spring data mongodb repository support --> <mongo:repositories base-package="com.mydata.repo.user" /> <!-- mongodb host --> <mongo:mongo host="${mongo.host.name}" port="${mongo.host.port}" /> <mongo:db-factory dbname="${mongo.db.name}" /> <!-- template performing mongodb operations --> <bean id="mongotemplate" class="org.springframework.data.mongodb.core.mongotemplate" c:mongo-ref="mongo" c:databasename="${mongo.db.name}" />
make sure configure appropriate writeconcern
on mongotemplate
or mongodbfactory
implementation.
the javadoc relevant mongotemplate
method here, 1 simplemongodbfactory
here.
Comments
Post a Comment