1

我正在使用 mongoRepository.save() 但无法获取重复项阻止插入时的错误信息。作为测试,我插入了一个重复的用户名,mongo 只是忽略了它。但是当用户名是唯一的时,它会按预期插入。

请参阅下面的我的服务类:

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 are found, silently 
            //ignores the query
            User saveduser = userRepo.save(newUser);


            //below is what I want but don't know how to get it from a repository
            //String error = template.getDb().getLastError().getErrorMessage();
            //return error;
            return null;


        }catch(Exception e){
            return e.getLocalizedMessage();
        }
    }


}

这是我的 UserRepository 接口:

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

这是我设置 MongoDbFactory 的 XML 文件:

<!-- 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 for performing MongoDB operations -->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"
        c:mongo-ref="mongo" c:databaseName="${mongo.db.name}" />
4

1 回答 1

0

确保您配置了适当WriteConcern的 onMongoTemplateMongoDbFactoryimplementation。

MongoTemplate相关方法的 JavaDoc 在这里,for 的一个SimpleMongoDbFactory这里

于 2013-08-16T17:00:31.910 回答