我有一个User
对象和Role
对象。每个用户都有一个角色。在数据库中,角色是表的外键roles
,其中每个角色只有数字 id 作为主键,以及角色的一些文本名称(“admin”、“user”)。
现在,我希望能够简单地POST
使用以下 JSON:
{"name": "John", "role": "admin"}
怎么做?
我最终遇到了这个错误:
Could not read document: Can not instantiate value of type [simple type, class Role] from String value ('admin'); no single-String constructor/factory method\n at [Source: java.io.PushbackInputStream@7b8a088a; line: 1, column: 17] (through reference chain: User[\"role\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, Role] from String value ('admin'); no single-String constructor/factory method\n at [Source: java.io.PushbackInputStream@7b8a088a; line: 1, column: 17] (through reference chain: User[\"role\"])
用户型号:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotNull
private String name;
@NotNull
@ManyToOne
private Role role;
// Getters and setters...
}
好榜样:
@Entity
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotNull
private String name;
// Getters and setters...
}