【问题标题】:Spring data rest @ManyToOne field is not coming in jsonSpring data rest @ManyToOne 字段不在 json 中
【发布时间】:2014-11-02 10:54:18
【问题描述】:

我正在使用 Spring Boot、Spring Data JPA 和 Spring Data Rest 技术开发一个 Web 项目。我能够成功设置所有内容并能够获取简单 POJO 的 JSON。我已经定制了两个类,使其具有像这样的 OneToMany 和 ManyToOne 关系:-

@Entity
@Table(name="t_profile")
public class Profile {
@Id
@column(name="profile_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
@JoinColumn(name = "cat_id", referencedColumnName = "category_id")
@ManyToOne(optional=false)
private Category category;

// getters and setters
}

@Entity
@Table(name="t_category")
public class Category {
 @Id
 @column(name="category_id")
 @GeneratedValue(strategy = GenerationType.AUTO)
 private long id;
 private String name;
 @OneToMany(mappedBy="category")
 private List<Profile> profile; 
 // getters and setters 
}
http://localhost:8080/project/profiles

当我使用 rest 客户端访问配置文件时;我能够获得带有 id 字段的 json 格式,名称但 ManyToOne 字段没有出现在 json 中,而在控制器中调试时,配置文件列表具有类别值。但它不是以 json 格式出现的。

有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    ManyToOne 字段将作为链接提供。即在访问类别时,配置文件字段将列在 JSON 正文中的“_links”下,如下所示:

    "_links" : {
        "profile" : {
            "href" : "http://<host>/<baseUrl>/category/<categoryId>/profile"
    }
    

    进一步获取 api 下面给定类别调用的配置文件详细信息:

    http://<host>/<baseUrl>/category/<categoryId>/profile
    

    【讨论】:

    • 谢谢,实际上我转向了另一种方式......在我的 json 中,即使是 _links,我也无法获取 manytoone 字段,因此我正在进行另一个 Web 服务调用以获取其他值。
    【解决方案2】:

    您可以在ManyToOne 字段中使用@RestResource(exported = false)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-15
      • 2015-12-07
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 2018-02-17
      • 2020-12-03
      • 2017-08-26
      相关资源
      最近更新 更多