0

我有一个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...
}
4

2 回答 2

3

除了更正您的 json 之外,我认为您至少需要两件事:一个 String 构造函数Role,以及带有on的@Column注释unique=trueRole.name

@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...
}

然后,您必须确保在保存 a 时从数据库中加载User正确Role的内容并替换为User.role,否则您可能会得到 a SQLIntegrityConstraintViolationException(因为您正在尝试保存Role一个名称已被占用的新实例)。

于 2015-12-04T10:41:07.457 回答
1

您的 json 无效,请将其更改为:

{
    "name": "John",
    "role": "admin"
}
于 2015-12-04T10:36:58.193 回答