13
votes

I want to hide the "id" item in the model, how to do this in java?

5
did you try @JsonIgnore?dharam
@dharam I want to partically hide, not all method hide the "id".Vision Yang
sorry! my method will do it for all references... need to do some custom code to get rid of it for just one flowdharam
@dharam yeah. For example, I have GET and POST, I want the "id" shows in the GET, but not POST, so I don't know how to do this.Vision Yang

5 Answers

12
votes

to hide a request field in Swagger API v2:

 @ApiModelProperty(hidden = true) 
 private String id;

in OpenAPI v3:

@Schema(accessMode = Schema.AccessMode.READ_ONLY)
private String id;
8
votes
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@ApiModelProperty(accessMode = ApiModelProperty.AccessMode.READ_ONLY)
private String id;

Also see: https://github.com/springfox/springfox/issues/2816

2
votes

You can use @Hidden with Swagger Core 2.X

@Hidden -- Hides a resource, an operation or a property

Example from above link : Marks a given resource, class or bean type as hidden, skipping while reading / resolving.

@Path("/user")
@Produces({"application/json", "application/xml"})
public class HiddenAnnotatedUserResourceMethodAndData {
    UserData userData = new UserData();

    @POST
    @Hidden
    @Operation(summary = "Create user",
            description = "This can only be done by the logged in user.")
    @Path("/1")
    public Response createUser(
            @Parameter(description = "Created user object", required = true) User user) {
        userData.addUser(user);
        return Response.ok().entity("").build();
    }

    @POST
    @Operation(summary = "Create user",
            description = "This can only be done by the logged in user.")
    @Path("/2")
    public Response createUserWithHiddenBeanProperty(
            @Parameter(description = "Created user object", required = true) UserResourceBean user) {
        return Response.ok().entity("").build();
    }
}

Output of above

openapi: 3.0.1
paths:
  /user/2:
    post:
      summary: Create user
      description: This can only be done by the logged in user.
      operationId: createUserWithHiddenBeanProperty
      requestBody:
        description: Created user object
        content:
          '*/*':
            schema:
              $ref: '#/components/schemas/UserResourceBean'
        required: true
      responses:
        default:
          description: default response
components:
  schemas:
    UserResourceBean:
      type: object
      properties:
        foo:
          type: string
0
votes

✍🏻 Extends yours Entity & Use @JsonIgnoreProperties

public class UserVo {

@JsonIgnoreProperties("password")
public static class Public extends User {}

@JsonIgnoreProperties("userId")
public static class Save extends User {}

@JsonIgnoreProperties("password")
public static class Update extends User {}

}

✍🏻 Entity Class ::

public class User implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer userId;

// 🚨 Write only access to password default in entity
// in order to hide it for update case we will extends class behaviour 
// in our custom views

// Instead of JsonViews i use custom views (i.e UserVo) with JsonProperty
// @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 


@NotBlank
@Schema(example = "lorem1234")
@Column(name = "password")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 
private String password; 

.....
}

✍🏻 Controller Class ::

// See UserVo.Save in request body it serialize this class

@PostMapping(value = "/create")
public ResponseModel<User> createUser(@Valid @RequestBody UserVo.Save user) {
 // ... My dirty code comes here 🤡
}

✍🏻 Result ::

  • Easy Serialization;
  • No separate Domain classes
  • Easy Swagger Schema Hide ( Swagger knows hide Id on Add Operation 😱)

======= Lastly would say Help Mankind ,Be Kind ! ========

0
votes

Generally using DTO can be useful in this situation, for each entity, define one DTO(it depends on your project but most of the time can be useful) and then map your entity to DTO and vice versa with Mapstruct,after that in your DTO class by using @JsonIgnorProperties annotation on each field you want, you can omit that field from exposing by API services.