the In this tutorial, we will show you how to create REST API with full Database CRUD functionality. We will start from configuration to database functionality step by step. If you are not familiar or not have a better knowledge about REST API please follow the REST API LINK to know more about REST web service. You can use any editor like Eclipse, Netbeans, IntelliJ as you are preferred with. In this tutorial, we will use IntelliJ for creating the REST API.

Create a New Project:

  1. Open IntelliJ and create a new project

     2. Select Maven project from the left side bar and click next

3. Write GroupId and ArtifactId, then click next. Please note GroupId + ArtifactId need to be unique so in that case, it is better to use any web URL which is really unique. In this project, we have used our website URL as GroupId, which is unique. If you want you can use any combination as your requirement.

     4. Write Project Name and choose a project directory, then click next.

Configure Spring Boot Project:

1. Open the pom.xml file to add required dependency

2. In the pom.xml file, you will find all the configuration information that is required to run the project. Like project deployment file type, add a dependency, changing project version number and more.

3. Add the following snippet right below version tag. Here we have used packaging tag as a jar, but if you want war file, then change it with war

<groupId>com.androgeeks</groupId>
<artifactId>restapi</artifactId>
<version>1.0-SNAPSHOT</version>
<name>RestAPI</name>
<packaging>jar</packaging>

4. By default Maven does not know it as Spring Boot Project, we have to add the following code snippet to let Maven know, that it is a Spring Boot project. When are adding the following snippet, maven will import all library and dependency from spring boot project.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.2.RELEASE</version>
</parent>

5. Please note every time you add some snippet on pom.xml file, you will be prompted with the following message. Select Import Changes from the dialog and IntelliJ will automatically download your required dependencies.

6. Add the <properties> tag right after the <parent> tag. And write the java version you want to use with the following project. In our case, we will be using java version 1.8

<properties>
    <java.version>1.8</java.version>
</properties>

Add Dependency:

1. Open pom.xml file, then add the following <dependencies> tag below <parent> tag.

<dependencies>
...
</dependencies>

2. To initiate the web service functionality we have to add the following code snippet inside the <dependencies> tag.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

First Run Project:

1. Create a package in “src/main/java” folder.

1. Create a main class in the newly created package folder.

2. Add the following code snippet in the MainApp class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * Created by fojlesaikat on 12/22/17.
 */
@SpringBootApplication
@EnableAsync
public class MainApp {
    
    public static void main(String[] args){
        SpringApplication.run(MainApp.class, args);
    }
    
}

3. To run the application we need to configure it first. First, click on the down arrow sign on the top right corner. And choose Edit Configurations

4. Then click on the + sign and choose Application type.

5. Then you will see a form, where you will see the Main class option. Just browse the Mmain class on the right side.

6. Then you will find the class that you created earlier inside the API folder. Select the class and press ok.

7. Then you will see the class on the Main lass label and press ok.

8. Click on the green play button on the top-right corner and run the application.

9. You will see the log message saying tomcat has started on port xxxx. By default, it starts on port 8080, but it can be changed with application.properties  file inside resources folder.

10. To change the port, first, add application.properties file inside resources folder.

11. Open application.properties file, then add the following line to change the port number.

server.port=9090

Now if you run the project you will see the project has started on port 9090.

 

Create Database:

Now create a sample database to interact with the project.

-- phpMyAdmin SQL Dump
-- version 4.6.5.2
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Jan 06, 2018 at 06:50 AM
-- Server version: 10.1.21-MariaDB
-- PHP Version: 5.6.30

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

 

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `rest_db`
--

-- --------------------------------------------------------

--
-- Table structure for table `assignment`
--

CREATE TABLE `assignment` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`type` varchar(20) NOT NULL,
`course_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- Table structure for table `course`
--

CREATE TABLE `course` (
`id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`duration` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;

-- --------------------------------------------------------

--
-- Table structure for table `student`
--

CREATE TABLE `student` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`roll` int(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- Table structure for table `student_course`
--

CREATE TABLE `student_course` (
`student_id` int(10) NOT NULL,
`course_id` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `assignment`
--
ALTER TABLE `assignment`
ADD PRIMARY KEY (`id`);

--
-- Indexes for table `course`
--
ALTER TABLE `course`
ADD PRIMARY KEY (`id`);

--
-- Indexes for table `student`
--
ALTER TABLE `student`
ADD PRIMARY KEY (`id`);

--
-- Indexes for table `student_course`
--
ALTER TABLE `student_course`
ADD PRIMARY KEY (`student_id`,`course_id`),
ADD UNIQUE KEY `course_id` (`course_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `assignment`
--
ALTER TABLE `assignment`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `course`
--
ALTER TABLE `course`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `student`
--
ALTER TABLE `student`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- Constraints for dumped tables
--

--
-- Constraints for table `student_course`
--
ALTER TABLE `student_course`
ADD CONSTRAINT `fk_studentcourse_course` FOREIGN KEY (`course_id`) REFERENCES `course` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_studentcourse_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Now write the following configuration on your application.properties to connect with database.

#REMOTE DB CONFIG
spring.datasource.url=jdbc:mysql://localhost:3306/rest_db
spring.datasource.username=root
spring.datasource.password=

We have not used any password for database configuration, because we are not using one.

Now add the following dependencies inside the pom.xml file, to make it work with the database.

<dependencies>

    <!-- JDBC Connect -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    <!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>com.monitorjbl</groupId>
        <artifactId>json-view</artifactId>
        <version>0.15</version>
    </dependency>

    <dependency>
        <groupId>com.sun.istack</groupId>
        <artifactId>maven-istack-commons-plugin</artifactId>
        <version>2.11</version>
    </dependency>


    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20150729</version>
    </dependency>

    <!-- Use MySQL Connector-J -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.40</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

</dependencies>

Create Models:

Now create a folder named inside modelapi folder. It is not necessary to have a folder name with nameModel. You can choose your own folder name. But in our case, we want all model(s) should be in the same folder. That’s why we have created the model folder inside the api folder. Then create the following three classes inside the model folder.

  • AssignmentModel
  • CourseModel
  • StudentModel

AssignmentModel.class

package api.model;

import javax.persistence.*;

/**
 * Created by fojlesaikat on 1/2/18.
 */
@Entity
@Table(name = "assignment")
public class AssignmentModel {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    long id;
    @Column(name = "name")
    String name;
    @Column(name = "type")
    String type;
    @ManyToOne
    CourseModel course;

    public AssignmentModel() {
    }

    public AssignmentModel(long id) {
        this.id = id;
    }

    public AssignmentModel(String name, String type) {
        this.name = name;
        this.type = type;
    }

    public AssignmentModel(String name, String type, CourseModel course) {
        this.name = name;
        this.type = type;
        this.course = course;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public CourseModel getCourseModel() {
        return course;
    }

    public void setCourseModel(CourseModel course) {
        this.course = course;
    }
}

CourseModel.class

package api.model;

import com.fasterxml.jackson.annotation.JsonBackReference;

import javax.persistence.*;
import java.util.List;

/**
 * Created by fojlesaikat on 1/6/18.
 */
@Entity
@Table(name = "course")
public class CourseModel {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    long id;
    @Column(name = "name")
    String name;
    @Column(name = "duration")
    String duration;
    @ManyToMany(mappedBy = "courseModels")
    @JsonBackReference
    List<StudentModel> studentModels;

    public CourseModel() {
    }

    public CourseModel(long id) {
        this.id = id;
    }

    public CourseModel(String name, String duration) {
        this.name = name;
        this.duration = duration;
    }

    public CourseModel(String name, String duration, List<StudentModel> studentModels) {
        this.name = name;
        this.duration = duration;
        this.studentModels = studentModels;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDuration() {
        return duration;
    }

    public void setDuration(String duration) {
        this.duration = duration;
    }

    public List<StudentModel> getStudentModels() {
        return studentModels;
    }

    public void setStudentModels(List<StudentModel> studentModels) {
        this.studentModels = studentModels;
    }
}

StudentModel.class

package api.model;

import com.fasterxml.jackson.annotation.JsonManagedReference;

import javax.persistence.*;
import java.util.List;

/**
 * Created by fojlesaikat on 1/6/18.
 */
@Entity
@Table(name = "student")
public class StudentModel {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    long id;
    @Column(name = "name")
    String name;
    @Column(name = "roll")
    String roll;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "student_course", joinColumns = @JoinColumn(name = "student_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "course_id", referencedColumnName = "id"))
    @JsonManagedReference
    List<CourseModel> courseModels;

    public StudentModel() {
    }

    public StudentModel(long id) {
        this.id = id;
    }

    public StudentModel(String name, String roll, List<CourseModel> courseModels) {
        this.name = name;
        this.roll = roll;
        this.courseModels = courseModels;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRoll() {
        return roll;
    }

    public void setRoll(String roll) {
        this.roll = roll;
    }

    public List<CourseModel> getCourseModels() {
        return courseModels;
    }

    public void setCourseModels(List<CourseModel> courseModels) {
        this.courseModels = courseModels;
    }
}

N:B: When using @ManyToOne annotation, please make sure variable name matches with the table name. Like CourseModel course where course should be matched with table name.

Create Repository:

Now create a folder named repository folder inside the api folder. It is not necessary to have a folder name with repository name. You can choose your own folder name. But in our case, we want all repository(s) should be in the same folder. That’s why we have created the repository folder inside the api folder. Then create the following three classes inside the repository folder.

  • AssignmentRepository
  • CourseRepository
  • StudentRepository

AssignmentRepository.class

package api.repository;

import api.model.AssignmentModel;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

/**
 * Created by fojlesaikat on 1/2/18.
 */
@Repository
public interface AssignmentRepository extends CrudRepository<AssignmentModel, Long> {
}

CourseRepository.class

package api.repository;

import api.model.CourseModel;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

/**
 * Created by fojlesaikat on 1/6/18.
 */
@Repository
public interface CourseRepository extends CrudRepository<CourseModel, Long> {
}

StudentRepository.class

package api.repository;

import api.model.StudentModel;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

/**
 * Created by fojlesaikat on 1/6/18.
 */
@Repository
public interface StudentRepository extends CrudRepository<StudentModel, Long> {
}

Create Services:

Now create a folder named service folder inside the api folder. It is not necessary to have a folder name with service name. You can choose your own folder name. But in our case, we want all service(s) should be in the same folder. That’s why we have created service folder inside the api folder. Then create the following three classes inside the repository folder.

  • AssignmentService
  • CourseService
  • StudentService

AssignmentService.class

package api.service;

import api.model.AssignmentModel;
import api.model.StudentModel;
import api.repository.AssignmentRepository;
import api.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * Created by fojlesaikat on 1/5/18.
 */
@Service
public class AssignmentService {

    @Autowired
    AssignmentRepository assignmentRepository;

    public long addAsssignment(AssignmentModel assignmentModel){
        return assignmentRepository.save(assignmentModel).getId();
    }

    public AssignmentModel getAssignment(long id){
        return assignmentRepository.findOne(id);
    }

    public List<AssignmentModel> getAllAssignment(){
        List<AssignmentModel> assignmentModels = new ArrayList<>();
        assignmentRepository.findAll().forEach(assignmentModels::add);
        return assignmentModels;
    }

    public long updateAssignment(AssignmentModel assignmentModel){
        return assignmentRepository.save(assignmentModel).getId();
    }

    public void deleteAssignment(long id){
        assignmentRepository.delete(id);
    }

}

CourseService.class

package api.service;

import api.model.CourseModel;
import api.repository.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fojlesaikat on 1/6/18.
 */
@Service
public class CourseService {

    @Autowired
    CourseRepository courseRepository;

    public long addCourse(CourseModel courseModel){
        return courseRepository.save(courseModel).getId();
    }

    public CourseModel getCourse(long id){
        return courseRepository.findOne(id);
    }

    public List<CourseModel> getAllCourse(){
        List<CourseModel> courseModels = new ArrayList<>();
        courseRepository.findAll().forEach(courseModels::add);
        return courseModels;
    }

    public void updateCourse(CourseModel courseModel){
        courseRepository.save(courseModel);
    }

    public void deleteCourse(long id){
        courseRepository.delete(id);
    }

}

StudentService.class

package api.service;

import api.model.StudentModel;
import api.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fojlesaikat on 1/6/18.
 */
@Service
public class StudentService {

    @Autowired
    StudentRepository studentRepository;

    public long addStudent(StudentModel studentModel){
        return studentRepository.save(studentModel).getId();
    }

    public StudentModel getStudent(long id){
        return studentRepository.findOne(id);
    }

    public List<StudentModel> getAllStudent(){
        List<StudentModel> studentModels = new ArrayList<>();
        studentRepository.findAll().forEach(studentModels::add);
        return studentModels;
    }

    public long updateStudent(StudentModel studentModel){
        return studentRepository.save(studentModel).getId();
    }

    public void deleteStudent(long id){
        studentRepository.delete(id);
    }

}

Create Controller:

Now create a folder named controller folder inside the api folder. It is not necessary to have a folder name with controller name. You can choose your own folder name. But in our case, we want all controller(s) should be in the same folder. That’s why we have created controller folder inside the api folder. Then create the following three classes inside the controller folder.

AssignmentController.class

package api.controller;

import api.model.AssignmentModel;
import api.model.CourseModel;
import api.model.Response;
import api.service.AssignmentService;
import api.service.CourseService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by fojlesaikat on 1/6/18.
 */
@RestController
@RequestMapping(value = "/assignment")
public class AssignmentController {

    @Autowired
    AssignmentService assignmentService;
    @Autowired
    CourseService courseService;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public Response createAssignment(@RequestBody String request){
        Response response = new Response();
        try {
            JSONObject jsonObject = new JSONObject(request);
            AssignmentModel assignmentModel = new AssignmentModel();
            assignmentModel.setName(jsonObject.optString("name"));
            assignmentModel.setType(jsonObject.optString("type"));
            CourseModel courseModel = courseService.isCourseExists(new CourseModel(jsonObject.optString("courseName"), jsonObject.optString("courseDuration")));
            if (courseModel == null) {
                long courseInsertId = courseService.addCourse(new CourseModel(jsonObject.optString("courseName"), jsonObject.optString("courseDuration")));
                courseModel = new CourseModel(courseInsertId);
            }
            assignmentModel.setCourseModel(courseModel);
            long assignmentInsertId = assignmentService.addAsssignment(assignmentModel);
            if (assignmentInsertId > 0) {
                response.setStatusCode(200);
                response.setStatusMessage("Success");
            } else {
                response.setStatusCode(500);
                response.setStatusMessage("Error");
            }
        }
        catch (Exception ex){
            response.setStatusCode(500);
            response.setStatusMessage("Success");
        }
        return response;
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<AssignmentModel> getAllAssignment(){
        return assignmentService.getAllAssignment();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public AssignmentModel getAssignment(@PathVariable("id") long id){
        return assignmentService.getAssignment(id);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Response updateAssignment(@RequestBody String request, @PathVariable("id") long id){
        Response response = new Response();
        try {
            JSONObject jsonObject = new JSONObject(request);
            AssignmentModel assignmentModel = new AssignmentModel();
            assignmentModel.setId(id);
            assignmentModel.setName(jsonObject.optString("name"));
            assignmentModel.setType(jsonObject.optString("type"));
            CourseModel courseModel = courseService.isCourseExists(new CourseModel(jsonObject.optString("courseName"), jsonObject.optString("courseDuration")));
            if (courseModel == null) {
                long courseInsertId = courseService.addCourse(new CourseModel(jsonObject.optString("courseName"), jsonObject.optString("courseDuration")));
                courseModel = new CourseModel(courseInsertId);
            }
            assignmentModel.setCourseModel(courseModel);
            long assignmentInsertId = assignmentService.addAsssignment(assignmentModel);
            if (assignmentInsertId > 0) {
                response.setStatusCode(200);
                response.setStatusMessage("Success");
            } else {
                response.setStatusCode(500);
                response.setStatusMessage("Error");
            }
        }
        catch (Exception ex){
            response.setStatusCode(500);
            response.setStatusMessage("Success");
        }
        return response;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void deleteAssignment(@PathVariable("id") long id){
        assignmentService.deleteAssignment(id);
    }

}

CourseController.class

package api.controller;

import api.model.CourseModel;
import api.model.Response;
import api.model.StudentModel;
import api.service.AssignmentService;
import api.service.CourseService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * Created by fojlesaikat on 1/5/18.
 */
@RestController
@RequestMapping(value = "/course")
public class CourseController {

    @Autowired
    CourseService courseService;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public Response addCourse(@RequestBody String request){
        Response response = new Response();
        try {
            JSONObject jsonObject = new JSONObject(request);
            CourseModel courseModel = new CourseModel();
            courseModel.setName(jsonObject.optString("name"));
            courseModel.setDuration(jsonObject.optString("duration"));
            long insertid = courseService.addCourse(courseModel);
            if (insertid > 0) {
                response.setStatusCode(200);
                response.setStatusMessage("Success");
            } else {
                response.setStatusCode(500);
                response.setStatusMessage("Error");
            }
        }
        catch (Exception ex){
            response.setStatusCode(500);
            response.setStatusMessage("Error");
        }
        return response;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public CourseModel getCourse(@PathVariable("id") long id){
        return courseService.getCourse(id);
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<CourseModel> getCourse(){
        return courseService.getAllCourse();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Response updateCourse(@RequestBody String request, @PathVariable("id") long id){
        Response response = new Response();
        try {
            JSONObject jsonObject = new JSONObject(request);
            CourseModel courseModel = new CourseModel();
            courseModel.setId(id);
            courseModel.setName(jsonObject.optString("name"));
            courseModel.setDuration(jsonObject.optString("duration"));
            long insertid = courseService.addCourse(courseModel);
            if (insertid > 0) {
                response.setStatusCode(200);
                response.setStatusMessage("Success");
            } else {
                response.setStatusCode(500);
                response.setStatusMessage("Error");
            }
        }
        catch (Exception ex){
            response.setStatusCode(500);
            response.setStatusMessage("Error");
        }
        return response;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void deleteCourse(@PathVariable("id") long id){
        courseService.deleteCourse(id);
    }

}

StudentController.class

package api.controller;

import api.model.CourseModel;
import api.model.Response;
import api.model.StudentModel;
import api.service.StudentService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fojlesaikat on 1/6/18.
 */
@RestController
@RequestMapping(value = "/student")
public class StudentController {

    @Autowired
    StudentService studentService;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public Response addStudent(@RequestBody String request){
        Response response = new Response();
        try {
            JSONObject jsonObject = new JSONObject(request);
            StudentModel studentModel = new StudentModel();
            studentModel.setName(jsonObject.optString("name"));
            studentModel.setRoll(jsonObject.optString("roll"));
            List<CourseModel> courseModels = new ArrayList<>();
            courseModels.add(new CourseModel("Course D", "9 Months"));
            courseModels.add(new CourseModel("Course K", "9 Months"));
            studentModel.setCourseModels(courseModels);
            long insertId = studentService.addStudent(studentModel);
            if (insertId > 0) {
                response.setStatusCode(200);
                response.setStatusMessage("Success");
            }
            else{
                response.setStatusCode(500);
                response.setStatusMessage("Error");
            }
        }
        catch (Exception ex){
            response.setStatusCode(500);
            response.setStatusMessage("Error");
        }
        return response;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public StudentModel getStudent(@PathVariable("id") long id){
        return studentService.getStudent(id);
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<StudentModel> getAllStudent(){
        List<StudentModel> studentModels = studentService.getAllStudent();
        return studentModels;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Response updateStudent(@RequestBody String request, @PathVariable("id") long id){
        Response response = new Response();
        try {
            JSONObject jsonObject = new JSONObject(request);
            StudentModel studentModel = new StudentModel();
            studentModel.setName(jsonObject.optString("name"));
            studentModel.setRoll(jsonObject.optString("12"));
            List<CourseModel> courseModels = new ArrayList<>();
            courseModels.add(new CourseModel("Course F", "16 Months"));
            courseModels.add(new CourseModel(2));
            studentModel.setCourseModels(courseModels);
            long insertId = studentService.addStudent(studentModel);
            if (insertId > 0) {
                response.setStatusCode(200);
                response.setStatusMessage("Success");
            }
            else{
                response.setStatusCode(500);
                response.setStatusMessage("Error");
            }
        }
        catch (Exception ex){
            response.setStatusCode(500);
            response.setStatusMessage("Error");
        }
        return response;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void deleteStudent(@PathVariable("id") long id){
        studentService.deleteStudent(id);
    }

}

 

Now run the maven project and call API from POSTMAN. You will receive all the data from the tables.