spring data jpa crud example

Example: how to perform crud operations in spring boot

package com.example.demo.com.example.demo.resource;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.com.example.demo.model.Student;
import com.example.demo.com.example.demo.repository.StudentRep;

@RestController
@RequestMapping(value = "/webapi")
public class StudentResource {
	
	@Autowired
	private StudentRep studentRep;
	
	@RequestMapping(method = RequestMethod.GET, value = "/getstudents")
	public List<Student> getStudents() {
		
		return studentRep.findAll();
		
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/addstudent")
	public String addStudent(@RequestBody Student student) {

		studentRep.save(student);
		return "Added Student : "+student.getName();
		
	}
	
	@RequestMapping(method = RequestMethod.GET,value = "/getstudents/{id}")
	public Optional<Student> getStudent(@PathVariable String id) {
		
		return studentRep.findById(id);
		
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/deletestudent/{id}")
	public String deleteStudent(@PathVariable String id) {
		
		studentRep.deleteById(id);
		
		return "Record Deleted :"+ id;
		
	}
	
	@RequestMapping(method = RequestMethod.PUT, value = "/updatestudent")
	public String updateStudent(@RequestBody Student student) {

		studentRep.findById(student.getId());
		
		if(studentRep.existsById(student.getId())) {
			studentRep.save(student);
			return "Record updated";
		}
		else {
			return "No record";
		}
		
		
	}
	
	
}

Tags:

Java Example