如何使用外键缩短REST JSON

时间:2015-12-04 10:25:52

标签: spring spring-data-jpa spring-rest

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

2 个答案:

答案 0 :(得分:3)

除了纠正你的json之外,我认为你至少需要两件事:Role的String构造函数和@Columnunique=true的{​​{1}}注释}

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 1}}(因为您尝试使用已经使用的名称保存新的SQLIntegrityConstraintViolationException实例)。

答案 1 :(得分:1)

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

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