【问题标题】:@Document Annotation for Collection Name in MongoDb for Java models Generated through Swagger in Spring boot Application@Document Annotation for Collection Name in MongoDb for Java models 通过 Spring boot Application 中的 Swagger 生成
【发布时间】:2021-07-30 16:15:13
【问题描述】:

我正在遵循的步骤

  1. 我为我的微服务编写 API 合同和定义模型的 Swagger 文件

  2. 现在我在我的 Spring 启动应用程序中使用 Swagger 代码生成依赖项,通过从 URL 读取 Swagger 来生成模型,该 URL 托管在“mvn install”上我的应用程序的目标(pom.xml 中提到的输出目录)目录中。

  3. 对于 Swagger 文件中的每个定义,将在我的应用程序的目标目录中生成一个模型类。

  4. 现在我使用 mongoDB 作为模型保存为集合的数据库。

  5. 需要为模型类动态提供@Document(value = "collection-name")。

  6. 由于模型类是通过 Swagger codegen 生成的,因此无法编辑这些,

那么如何为要保存在数据库中的定义维护动态名称 有没有办法通过 Swagger Contract 来定义这个?

【问题讨论】:

    标签: java mongodb spring-boot swagger swagger-codegen


    【解决方案1】:

    前段时间我也在为同样的问题苦苦挣扎,some solutions 包括对生成的文件进行后处理。

    但是,出于安全考虑,将 MongoDB 模型暴露给 API 可能并不完全正确。一个有趣的方法是简单地使用 Mappers 并将 DTO 概念应用于自动生成的模型类。

    例如:

    假设您在 MongoDB 中有一个 users 集合,以及一个用于检索用户的 API。

    components:
      schemas:
        User:
          type: object
          properties:
            id:
              type: string
            name:
              type: string
    

    Swagger 自动生成的类是这样的:

    package api;
    
    @ApiModel()
    @Validated
    public class User   {
      @JsonProperty("id")
      private String id = null;
    
      @JsonProperty("name")
      private String name = null;
    }
    

    您还将拥有“标准”用户模型类:

    package model;
    
    @Document(collection = "users")
    public class User {
        @Id
        private String id;
        @NotNull
        private String name;
        @NotNull
        private String password;
    }
    

    例如,请注意密码字段不包含在 API 定义中。

    然后我们将拥有典型的用户存储库:

    public interface UserRepository extends MongoRepository<User, String> { }
    

    现在我们必须实现映射器,使用MapStruct 非常简单:

    @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
    public interface UserMapper {
        api.User map(model.User user);
    }
    

    您可以广泛自定义映射哪些信息以及如何映射信息。

    唯一剩下的是控制器:

    @Controller
    public class MyController implements MyApi {
    
        @Inject
        UserMapper mapper;
    
        @Autowired
        private UserRepository repository;
    
        @GetMapping("/api/v1.0/users")
        public ResponseEntity<List<api.User>> getAllUsers() {
            List<api.User> users = new ArrayList<>();
            repository.findAll().forEach(user -> users.add(mapper.map(user)));
            return new ResponseEntity(users, HttpStatus.OK);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-06
      • 2021-06-27
      • 2021-05-18
      • 2017-10-30
      • 2016-09-20
      • 1970-01-01
      • 2019-05-27
      • 2016-08-13
      • 1970-01-01
      相关资源
      最近更新 更多