我有一个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...
}
发布于 2015-12-04 18:41:07
除了纠正您的json之外,我认为您至少需要两样东西:Role
的字符串构造函数,以及Role.name
上带有unique=true
的@Column
批注
@Entity
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(unique=true, nullable=false)
private String name;
public Role() {}
public Role(String name) {
this.name = name;
}
// Getters and setters...
}
然后,您必须确保在保存User
时,从数据库加载了正确的Role
并将其替换为User.role
,否则您可能会得到一个SQLIntegrityConstraintViolationException
(因为您正在尝试使用已采用的名称保存一个新的Role
实例)。
发布于 2015-12-04 18:36:58
您的json无效,请将其更改为:
{
"name": "John",
"role": "admin"
}
https://stackoverflow.com/questions/34086137
复制相似问题