Saltar al contenido

Ejemplo de operaciones Spring Boot CRUD sin base de datos

Ejemplo: cómo realizar operaciones de crud en 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";
		}
		
		
	}
	
	
}
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *