简体   繁体   English

Spring 数据 REST 自定义 POST 实体

[英]Spring Data REST customize POST entity

I'm using Spring Data Rest 3.3.1.我正在使用 Spring 数据 Rest 3.3.1。

I have domain object (this is just an example):我有域 object(这只是一个例子):

@Data @Getter @Setter
@Entity
public class Figure {
  @Id private long id;
  private int volume;
}

And I have repository for this entity:我有这个实体的存储库:

@RepositoryRestResource
public interface FigureRepository extends CrudRepository<Figure, Long> {}

So, spring automatically creates method for POSTing Figure entity.因此,spring 自动创建 POSTing Figure 实体的方法。 For example:例如:

POST localhost:8080/figures
{
  "volume": 1000
}

But I want to pass customized object to POST method and convert it to needed entity, for example但我想将自定义的 object 传递给 POST 方法并将其转换为所需的实体,例如

POST localhost:8080/figures
{
  "length": 10,
  "width": 10,
  "height": 10
}

and example of converter:和转换器的例子:

class FigureDtoConverter implements Converter<FigureDto, Figure> {
  @Override
  Figure convert(FigureDto dto) {
    Figure f = new Figure();
    f.setVolume(dto.getLength() * dto.getWidth() * dto.getHeight());
    return f;
  }
}

How can I do this without creating custom controller?如何在不创建自定义 controller 的情况下做到这一点? Because if I create controller I lost useful spring features like event handling, validating etc因为如果我创建 controller 我失去了有用的 spring 功能,如事件处理、验证等

No way.没门。 You must create your controller.您必须创建 controller。

Use different request mapping path instead of /figures can keep Spring Data REST endpoints使用不同的请求映射路径而不是/figures可以保留 Spring 数据 REST 端点

POST localhost:8080/figures
{
  "volume": 1000
}
POST localhost:8080/create-figure-by-measurement
{
  "length": 10,
  "width": 10,
  "height": 10
}

Create a POJO containing the fields you want to pass.创建一个包含要传递的字段的 POJO。

public class Edges {
    Integer length;
    Integer width;
    Integer height; //getters and setters

}

You can make a post request with this你可以用这个发出post请求

{
  "length": 10,
  "width": 10,
  "height": 10
}

And get the object of the Edges in your controller and convert it to Figure并获取 controller 中Edges的 object 并将其转换为Figure

@PostMapping("/figure")
public String getEdges(@RequestBody Edges edges){
    //...
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM