Yassin Hajaj
Yassin Hajaj

Reputation: 21975

Spring Controller - Map JSON Attribute to foreign key Entity

UserController.java

@RestController
@RequestMapping("/users")
public class UserController {
    // code
    @PostMapping("/sign-up")
    public void signUp(@RequestBody User user) {
        //code
    }
}

User

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private long id;

    @ManyToOne
    @JoinColumn(name = "language_id")
    private Language language;

    // others
    public User() {
    }
}

So, as you see, Language is an independent entity. But I want to be able to send the following JSON structure

{
    "foreName" : "bla",
    "sureName" : "blo",
    "language" : "1"
}

But I receive the following error

Cannot construct instance of entity.db.user.Language (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1');

Do I need to go through a filter to fetch the Language entity beforehand? Is there a form to force a parsing method? What is the way to do it properly here?

Upvotes: 4

Views: 854

Answers (1)

Prakash Ayappan
Prakash Ayappan

Reputation: 455

Create a new DTO Object, Say UserDTO, as Request Body in your API Method. Process the DTO to form the User entity, to proceed further.

Upvotes: 2

Related Questions