首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用外键缩短REST JSON

如何使用外键缩短REST JSON
EN

Stack Overflow用户
提问于 2015-12-04 18:25:52
回答 2查看 826关注 0票数 0

我有一个User对象和一个Role对象。每个用户都有一个角色。在数据库中,角色是表roles的外键,其中每个角色只有数字id作为主键,以及角色的一些文本名称("admin","user")。

现在,我希望能够简单地POST以下JSON:

代码语言:javascript
复制
{"name": "John", "role": "admin"}

如何做到这一点?

我最终得到了这个错误:

代码语言:javascript
复制
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\"])

用户模型:

代码语言:javascript
复制
@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...
}

角色模型:

代码语言:javascript
复制
@Entity
@Table(name = "roles")
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @NotNull
    private String name;

    // Getters and setters...
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34086137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档