【问题标题】:Spring Boot MongoDb repository findAll() returns empty listSpring Boot MongoDb 存储库 findAll() 返回空列表
【发布时间】:2021-06-27 12:41:36
【问题描述】:

我有一个针对 MongoDb 实例运行的 Spring Boot 应用程序。

从 MongoRepository 调用 findAll() 方法时,存储库返回一个空列表,而我在集合中有一个文档。

启动时与数据库的连接工作正常。 我检查了文档,不知道问题出在哪里。

存储库:

@Repository
public interface UserDao extends MongoRepository<User, String>{

}

服务:

@Component
@Slf4j
public class UserServiceImpl implements IUser {
    @Autowired
    UserDao userDao;

    @Override
    public List<User> getAllUsers() throws Exception {

        // 1: Initialisation
        log.info("[ getAllUsers ] Start");
        List<User> response = new ArrayList<User>();

        // 2: call Dao
        try {
            log.debug("Calling user Dao to select all users");
            response = userDao.findAll();
        } catch (Exception e) {
            log.error(Constants.COMMENT_SELECTION_ERROR, e);
            throw new Exception(Constants.COMMENT_SELECTION_ERROR, e);
        }

        // 3: Cloture
        log.debug("Response: count of users :{} ", response.size());
        log.info("[ getAllUsers ] End :: Success");
        return response;
    }

控制器:

@RestController
@Slf4j
@SuppressWarnings("rawtypes")
@RequestMapping(value = "/api/v1/user")
public class UserApiController {

    @Autowired
    private IUser sUser;

    @ApiOperation(value = "getAllUsers", response = ResponseEntity.class)
    @ApiResponses(value = { @ApiResponse(code = 200, message = "selection successful", response = User.class),
            @ApiResponse(code = 400, message = "Required parameter does not exist or is not in the expected format", response = User.class),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource", response = User.class),
            @ApiResponse(code = 406, message = "The resource you were trying to reach is not found", response = User.class),
            @ApiResponse(code = 500, message = "Accessing the resource you were trying to reach is forbidden") })
    @RequestMapping(value = "/getAllUsers", method = RequestMethod.GET, produces = "application/json")
    ResponseEntity<List<User>> getAllUsers() {
        log.info("[ getAllUsers ] Start");
        List<User> responseListUsers = new ArrayList<>();
        try {
            responseListUsers = sUser.getAllUsers();
            log.info("[ getAllUsers ] End :: Success");
            return new ResponseEntity<>(responseListUsers, HttpStatus.OK);
        } catch (Exception se) {
            log.error("[ getAllUsers ] End :: ERROR", se.getMessage());
            return new ResponseEntity<>(responseListUsers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

型号:

@ApiModel(value = "User", description = "User Model")
@Data
@Document
@NoArgsConstructor
public class User {

    String id;
    /**
     * The user name
     *
     * @param name: The user name
     * @return the current value of the name
     */
    @ApiModelProperty(value = "name", required = true)
    @NotBlank
    private String name;
    /**
     * The user address
     *
     * @param address: The user address
     * @return the current value of the address
     */
    @ApiModelProperty(value = "address", required = true)
    @NotBlank
    private String address;
    /**
     * The user phone
     *
     * @param phone: The user phone
     * @return the current value of the phone
     */
    @ApiModelProperty(value = "phone", required = true)
    @NotNull
    @Pattern(regexp = Constants.PHONE_FORMAT)
    private String phone;
    /**
     * The user job
     *
     * @param job: The user function
     * @return the current value of the user job
     */
    @ApiModelProperty(value = "job", required = true)
    @NotBlank
    private String job;
    /**
     * The name of the agency to which the user is attached
     *
     * @param agency: The name of the agency to which the user is attached
     * @return the current value of the agency
     */
    @ApiModelProperty(value = "agency", required = true)
    @DBRef
    private Agency agency;
}

收藏:

日志显示没什么有趣的,当我点击 http://localhost:8080/api/v1/user/getAllUsers 时,我只得到以下日志:

2021-03-31 15:51:51.023 INFO 19804 --- [nio-8080-exec-1] c.c.airbnb.controller.UserApiController : [getAllUsers] 开始

2021-03-31 15:51:51.025 INFO 19804 --- [nio-8080-exec-1] c.c.airbnb.service.impl.UserServiceImpl : [ getAllUsers ] 开始

2021-03-31 15:51:51.035 INFO 19804 --- [nio-8080-exec-1] c.c.airbnb.service.impl.UserServiceImpl : [ getAllUsers ] End :: 成功

2021-03-31 15:51:51.037 INFO 19804 --- [nio-8080-exec-1] c.c.airbnb.controller.UserApiController : [ getAllUsers ] End :: 成功

【问题讨论】:

  • 使用@Service 而不是@Component。你的模型显示String id; 但在数据库中它是一个ObjectId> 如果你需要字符串,那么你可以使用@Id String _id=UUID.randomUUID().toString()

标签: mongodb spring-boot


【解决方案1】:

您的模型类中似乎缺少@javax.persistence.Id,如下所示:

@ApiModel(value = "User", description = "User Model")
@Data
@Document
@NoArgsConstructor
public class User {
    @Id
    String id;
    ...
}

【讨论】:

  • 我在org.springframework.data.annotation.Id中添加了Id注解,重启后还是不行
  • 我有典型的架构,控制器调用服务调用存储库。我已经在帖子中添加了这些。日志显示没有任何有趣的内容,没有抛出异常但列表为空。
【解决方案2】:

在数据库方面,我的用户文档没有通过 Id 指向特定机构。 看起来当你定义一个包含指向另一个模型的@DbRef 属性的模型时,数据库中的文档必须正确填充一个指向父实体的 id,否则 findAll() 方法将忽略该文档。 现在可以了。

【讨论】:

    猜你喜欢
    • 2021-09-03
    • 2020-06-15
    • 2022-06-15
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 2022-01-13
    • 2019-11-23
    • 1970-01-01
    相关资源
    最近更新 更多