Spring Controller

编程入门 行业动态 更新时间:2024-10-24 21:30:43
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.

更多推荐

本文发布于:2023-08-06 09:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1446697.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Spring   Controller

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!