Spring data rest @ManyToOne field is not coming in json

落爺英雄遲暮 提交于 2019-12-10 22:32:39

问题


I am developing a web project using Spring Boot, Spring Data JPA and Spring Data Rest technologies. I am able to setup everything successfully and able to get JSON of a simple POJOs. I have customized two classes to have OneToMany and ManyToOne relationship like this:-

@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

When I am accessing profiles using rest client; I am able to get json format with field of id, name but ManyToOne field is not coming in json, whle debugging in controller, profile list has values of category. But it is not coming in json.

Any thoughts?


回答1:


ManyToOne field will comes as a link. That is on accessing category, profile field will be listed under "_links" in JSON body like shown below:

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

Further to get details of profile for a given category call below api:

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



回答2:


you can use @RestResource(exported = false) in you ManyToOne field.



来源:https://stackoverflow.com/questions/25737500/spring-data-rest-manytoone-field-is-not-coming-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!