chumakoff
chumakoff

Reputation: 7054

Having more control over "@RequestBody Entity entity" when creating/updating a record

I am switching to Java/Spring from another development stack and I am very confused about how in Spring some things are done.

One of the issues is the magical conversion of request body parameters into a Java object (entity) with the @RequestBody annotation.

See the following example

@PostMapping
public User create(@RequestBody User user) {}

@PutMapping
public User update(@RequestBody User user) {}

The issue is that I cannot control which parameters come from a request, thus how the User entity is built.

The User entity may have lots of fields and associations, e.g.

    {
      "name": "John Doe",
      "age": 33,
      "email": "[email protected]",
      "addresses": [{
        "street": "XYZ Main St",
        "city": "Test City",
        "zip": "12345"
      }]
    }

What if I want to have a create/update endpoint that can only set/modify name and age, and no other fields and associations?

At the same time I might need to have another controller for admins that can set/modify all User fields and associations shown above.

How can I control what is coming in request body and how a User record is initialized?


I know that I can use things like UserDto:

public class UserDTO {    
    private String name;
    private Integer age;
}

// Controller
@PostMapping
public User create(@RequestBody UserDto userDto) {}

But how combine this approach with @Valid- related annotations (and others) which are defined in the entity class (User), so I cannot do validation in this way: create(@Valid @RequestBody UserDto userDto).

Or should I define validation rules as well as field sets in DTOs?

And should I create DTOs for all possible endpoints and business cases, e.g.

public class UserDTO {    
    private String name;
    private Integer age;
}

public class AdminUserDTO {    
    private String name;
    private Integer age;
    private String email;

    private List<Address> addresses;
}

From my experience, a good solution would be to get all request parameters 'as-is' (as a HashMap maybe) and initialize a new entity (or modify an existing entity) explicitly to have the full control. Can I explicitly specify a list of allowed parameters? Is there a way to specify which parameters are required and which are optional?

Upvotes: 0

Views: 53

Answers (0)

Related Questions