首页 > 解决方案 > Swagger annotation traversing all tables in DB

问题描述

I'm having a look at a Java application that provides a REST API to access a database. Besides JAX-RS, it uses Swagger for generating the documentation and the testing website. On one of the routes, I've realized that the result example given by Swagger is extremely long (more than 140000) lines:

Swagger problem

This route is defined with the following code:

@GET
@Path("/getUsers")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Operation(
        summary = "Get available users",
        responses = {
                @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = OauthClientDetailsEntity.class)), description = "Get users list"),
                @ApiResponse(responseCode = "401", content = @Content(schema = @Schema(implementation = ErrorResponse.class)), description = "Error: Unauthorized"),
                @ApiResponse(responseCode = "500", description = "Error: Internal Server Error")
        }
)
public Response getUsers() {
  // ....
}

The "trouble-maker" is the idCliente field, which is defined like this in the entity class:

@JoinColumn(name = "idCliente", referencedColumnName = "id")
@ManyToOne
private Cliente idCliente;

The table Cliente (customer in English) is related to a lot of tables in the DB, so I think that the problem is that Swagger is traversing all this tables, so the example result is so long. The class has more than 40 fields, and it looks like this:

@Entity
@Table(name = "cliente")
@XmlRootElement
public class Cliente implements Serializable {
    @OneToMany(mappedBy = "idCliente")
    private List<FacturaCliente> facturaClienteList;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idCliente")
    private List<OauthClientDetailsEntity> oauthClientDetailsEntityList;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "cliente")
    private List<OauthAccessTokenEntity> oauthAccessTokenEntityList;

    @Column(name = "codigoPlantillaFacturacion")
    private String codigoPlantillaFacturacion;
    // etc...
}

I'm new to Swagger, so I'm not sure about how to deal with this problem. Is there any way to make Swagger not traverse all the related tables? Or, what other approach would be more efficient?

Thanks in advance,

标签: javaswaggerjax-rs

解决方案


You can ignore this field with @ApiModelProperty(hidden=true) but you have to be aware that all that content will be rendered anyway. If you don't need this field better approach will be not to render it (e.g. @JsonIgnore annotation). The best option is to return DTO only with necessary fields instead of whole entity with its hierarchy.


推荐阅读