I am new to java and springboot. I am trying to create one CRUD application using springboot. I am using MySQL for storing the data.
Employee Model -
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email_id")
private String emailId;
public Employee() {
}
public Employee(String firstName, String lastName, String emailId) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
Employee Repository -
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.raksh.springboot.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
Employee Controller -
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.raksh.springboot.model.Employee;
import com.raksh.springboot.repository.EmployeeRepository;
@CrossOrigin(origins = "http://localhost:3000/")
@RestController
@RequestMapping("/api/v1/")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
// get all employees
@GetMapping("/employees")
public List<Employee> getAllEmployees(){
return employeeRepository.findAll();
}
}
The above controller is giving me the result in the JSON array of objects form as shown below
[
{
"id": 1,
"firstName": "Tony",
"lastName": "Stark",
"emailId": "tony@gmail.com"
},
{
"id": 2,
"firstName": "Thor",
"lastName": "Odinson",
"emailId": "thor@asgard.com"
}
]
But I need the response in the below form
{
total_items: 100,
has_more: true,
employees : {
1 : {
"id": 1,
"firstName": "Raksh",
"lastName": "Sindhe",
"emailId": "raksh@gmail.com"
},
2: {
"id": 2,
"firstName": "Thor",
"lastName": "Odinson",
"emailId": "thor@asgard.com"
}
}
}
Really appreciate the help.