Spring Controller - 将JSON属性映射到外键实体(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() { } }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?
最满意答案
在API方法中创建一个新的DTO对象Say UserDTO作为Request Body。 处理DTO以形成用户实体,以进一步继续。
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.
更多推荐
发布评论