Spring REST API,响应中的自定义实体字段

Spring REST API, custom entity fields in the response

我在 REST API(Java、SpringBoot、QueryDsl...)中工作,我想自定义结果中的字段。默认情况下,我正在获取实体的所有字段,但我需要的字段取决于请求。这应该是动态的。

据我所知,使用投影我可以获得类似的东西,但我必须事先声明投影并且我想使用动态而非静态的东西。另一方面,我看到像 GraphQL 这样的东西允许这种行为,但我必须重构一切。

以前有人遇到过这个问题吗?

这是我的代码:

BaseRestCRUDController

public abstract class BaseRestCRUDController<T extends EntityBase, V extends BaseDTO> {

@GetMapping("/list")
  public ResponseEntity<List<V>> findAll(Predicate predicate, Pageable pageable) {
    log.info("FindAll");
    return new ResponseEntity(getCRUDService().findAll(predicate, pageable), HttpStatus.OK);
  }

}

示例控制器

@RestController
@RequestMapping("/api/example")
public class ExampleController
    extends BaseRestCRUDController<Example, ExampleDTO> {

  @Autowired 
  private ExampleService ExampleService;

  @Override
  public ResponseEntity<List<ExampleDTO>> findAll(
      @QuerydslPredicate(root = Example.class) Predicate predicate, Pageable pageable) {
     return super.findAll(predicate, pageable);
  }

  @Override
  protected CRUDService<Example, ExampleDTO> getCRUDService() {
    return ExampleService;
  }
  
}

示例(实体)

public class Example {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(name = "name", nullable = false)
  private String name;

  @Column(name = "creation_date")
  private Instant creationDate;

  @Column(name = "last_update")
  private Instant lastUpdate;

  @Column(name = "erasure_date")
  private Instant erasureDate;
}
[
    {
        "id": 1,
        "name": "e1",
        "creationDate": "2021-11-15T23:00:00Z",
        "lastUpdate": null,
        "erasureDate": null
    },
    {
        "id": 2,
        "name": "e2",
        "creationDate": "2021-11-15T23:00:00Z",
        "lastUpdate": null,
        "erasureDate": null
    },
    {
        "id": 3,
        "name": "e3",
        "creationDate": "2021-11-15T23:00:00Z",
        "lastUpdate": null,
        "erasureDate": null
    }
]

如何在不使用投影的情况下获得这样的东西?

http://localhost:8080/api/example/list?fields=id,name&page=1&size=10&sort=id,desc

[
    {
        "id": 1,
        "name": "e1"
    },
    {
        "id": 2,
        "name": "e2"
    },
    {
        "id": 3,
        "name": "e3"
    }
]

http://localhost:8080/api/example/list?fields=name&page=1&size=10&sort=id,desc

[
    {
        "name": "e1",
    },
    {
        "name": "e2",
    },
    {
        "name": "e3",
    }
]
 @Ignore
 private Instant creationDate;

试试这个。 您可以在 getter、setter 或字段上使用 @Ignore。