Spring data rest @ManyToOne 字段不在 json 中

Posted

技术标签:

【中文标题】Spring data rest @ManyToOne 字段不在 json 中【英文标题】:Spring data rest @ManyToOne field is not coming in 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 格式出现的。

有什么想法吗?

【问题讨论】:

【参考方案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)

【讨论】:

以上是关于Spring data rest @ManyToOne 字段不在 json 中的主要内容,如果未能解决你的问题,请参考以下文章

排除 Spring-data-rest 资源的部分字段

如何在 Spring-Data-Rest 中实现细粒度的访问控制?

初入spring boot(八 )Spring Data REST

Spring-Data-Rest中时间的数据类型

您如何保护 Spring Boot / Spring-Data Rest 以便用户只能访问他自己的实体

spring-data-rest 集成测试因简单的 json 请求而失败