I am new to development of REST webservices. Currently, we are using Spring Boot, Spring JPA for the development of services. I am facing difficulty in returning selective columns in the REST response. My problem is as below:
I have a user table with 10 rows with below columns
- Id
- Name
- Age
- City
- Mobile number
My user Entity object is:
@Entity
@Table(name="user")
public class User
{
@Id
@GeneratedValue(generator="ID", strategy=GenerationType.SEQUENCE)
private long id;
@Column(name="Name")
private string name;
@Column(name="age")
private int age;
@Column(name="city")
private string city;
@Column(name="mobile number")
private string mobileNumber;
.
.
.
getter and setters
.
.
.}
I have below two requirements to develop:
- To return all the rows with all the columns
- To return all the rows with only three columns (Id, Name and mobile number)
For the first requirement, I was able to get it working by using the findAll() of JPA
For the second requirement, I tried using a custom query as below:
@Query("select New com.org.user(u.id, u.name, u.mobileNumber) from user u")
public List<user> getList()
With this, my Json response was looking as below with the other two fields (city and age) having default values but not the actual values in table.
[
{
"id": 1,
"name":"Rocky"
"age":0,
"city":null,
"mobileNumber": "9080980909"
},
{
"id": 2,
"name":"Stella"
"age":0,
"city":null,
"mobileNumber": "8909012239"
}
.
.
.
.
{
"id": 10,
"name":"Una"
"age":0,
"city":null,
"mobileNumber": "78976887989"
}
]
But I need the response to be like below to contain only three fields
[
{
"id": 1,
"name":"Rocky",
"mobileNumber": "9080980909"
},
{
"id": 2,
"name":"Stella",
"mobileNumber": "8909012239"
},
.
.
.
{
"id": 10,
"name":"Una",
"mobileNumber": "78976887989"
}
]
Can someone please help as to how can i get the response as above?