I'm using Spring Data Rest 3.3.1.
I have domain object (this is just an example):
@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. 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
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? Because if I create controller I lost useful spring features like event handling, validating etc
No way. You must create your controller.
Use different request mapping path instead of /figures
can keep Spring Data REST endpoints
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.
public class Edges {
Integer length;
Integer width;
Integer height; //getters and setters
}
You can make a post request with this
{
"length": 10,
"width": 10,
"height": 10
}
And get the object of the Edges
in your controller and convert it to Figure
@PostMapping("/figure")
public String getEdges(@RequestBody Edges edges){
//...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.