Priya Priya - 1 year ago 74
Java Question

how to restrict access some fields of child entities and parent entities through spring rest api

if I hit an API that is displaying all the details of child entities with parent entity [Mapping may OneToOne or ManyToOne etc..]. I am getting output like this..

{
"fID": 19,
**"comments": "good",**
"recommendation": "rec",
"candidate": {
"candidateID": 400,
"firstName": "Raghu",
"lastName": "R",
"emailID": "[email protected]",
"phoneNumber": "9900000099",
**"password": "Hello",**
"gender": "1",
"candidateDOB": 1472169600000,
"userId": 22
},
"inter": {
"interID": 14,
**"name": "Anu",**
"designation": "Dev"
},
"Job": {
"id": 13,
"maxYearOfExperience": 9,
"minYearOfExperience": 3,
**"organizationName": "EFG"**
}
}


my code is:

Query query = session.createQuery("from EntityName where ID= :id");
query.setInteger("id", id);
result = query.uniqueResult();


I want to hide displaying the fields, bold letters [** **] in the above output..
I tried some methods, :

1st method is :

EntityName example = new EntityName();
Example ex = Example.create(example).excludeProperty("password");
Criteria criteria = session.createCriteria(EntityName.class)
.add(Restrictions.eq("id", id))
.add(ex);
EntityName= (EntityName) criteria.uniqueResult();


But this approach is not working as my requirement.

2nd method is:

Criteria criteria = session.createCriteria(EntityName.class)
.add(Restrictions.eq("id", id));
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("id"));
projList.add(Projections.property("Name"));
projList.add(Projections.property("authPerson"));
projList.add....so on
criteria.setProjection(projList);

Object obj = criteria.uniqueResult();
if(obj != null){
EntityName= (EntityName) obj;
}


Is there any other way to solve this?
Thanks in advance.

Answer Source

You can do this using the @JsonIgnore and @JsonProperty annotations inside your parent entity. How exactly you do this will depend on what version of Jackson you are using. Have a look at this answer for the options you have:

Only using @JsonIgnore during serialization, but not deserialization

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download