簡體   English   中英

Spring Boot JSON多對一

[英]Spring Boot JSON Many to one

我的代碼有問題...

我使用Spring Boot和Angularjs創建單頁應用程序。

這是我的用戶類:

@Entity
@Table(name = "admins")
public class Admin {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer adminid;
    private String name;
    private String surname;
    private String email;
    private String login;
    private String password;

    @ManyToOne
    @JoinColumn(name = "groupid")
    private Group groupid;
    private Boolean active;
    @Temporal(TemporalType.TIMESTAMP)
    private Date modifydate;
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdate;

    public Admin() {
    }
   //setters ang getters
  }

我的第二實體類看起來

@Entity
@Table(name = "groups")
public class Group {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer groupid;
private String groupname;
@Temporal(TemporalType.TIMESTAMP)
private Date modifydate;
@Temporal(TemporalType.TIMESTAMP)
private Date createdate;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "groupid")
@JsonIgnore
private List<Admin> groupusers;

public Group() {
}

public Group(Integer groupid) {
    this.groupid = groupid;
}
}

我的前端應用程序將請求發送到服務器,像這樣

   {adminid: null, name: "dsa", surname: "dsa", email: "d", login: "sada", groupid: "1", active: true}

嘗試添加新管理員時,groupid屬性出現問題。

 WARN 27742 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not construct instance of com.patryk.model.Group: no String-argument constructor/factory method to deserialize from String value ('1')
  at [Source: java.io.PushbackInputStream@9fe378; line: 1, column: 83] (through reference chain: com.patryk.model.Admin["groupid"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.patryk.model.Group: no String-argument constructor/factory method to deserialize from String value ('1')
  at [Source: java.io.PushbackInputStream@9fe378; line: 1, column: 83] (through reference chain: com.patryk.model.Admin["groupid"])

我的控制器:

 @RestController
 @RequestMapping("/api/admins")
 public class AdminController {

@Autowired
private AdminService adminService;


@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> addUser(@RequestBody Admin admin)
{
    adminService.save(admin);
    return new ResponseEntity<Admin> (admin,HttpStatus.OK);
}
}

我如何找到解決方案? 有人知道我在做什么錯嗎?

您必須從groupid構造對象。

{
   adminid: null, 
   name: "dsa", 
   surname: "dsa", 
   email: "d", 
   login: "sada", 
   groupid: { "groupid": "1"}, 
   active: true
}

如果要保留無法使用的原始json,則需要創建一個自定義反序列化器,以便可以將"groupid": "1"轉換為Group實體。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM