如何用外键缩短 REST JSON

How to shorten REST JSON with foreign keys

我有一个 User 对象,还有一个 Role 对象。每个用户都有一个角色。在数据库中,角色是 table 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...
}

你的json无效,改成这样:

{
    "name": "John",
    "role": "admin"
}

除了更正您的 json,我认为您至少需要两件事:Role 的 String 构造函数,以及带有 unique=true@Column 注释Role.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...
}

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