Sunny Yadav
Sunny Yadav

Reputation: 55

Spring data rest @ManyToOne field is not coming in json

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?

Upvotes: 5

Views: 2405

Answers (2)

oussama barrady
oussama barrady

Reputation: 31

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

Upvotes: 3

charybr
charybr

Reputation: 1948

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

Upvotes: 1

Related Questions