Descripción
Create a Spring Boot RestController with CRUD endpoints returning ResponseEntity
File Template: ✅
Prefix
spring:rest
Scopes
java
Snippet de código
package ${1:com.example.demo.restcontroller};
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import ${2:com.example.demo.service.${3:MyService}};
import ${4:com.example.demo.model.${5:MyEntity}};
import java.util.List;
@RestController
@RequestMapping("${6|/api,/api/v1,/api/v2|}/${7:base-path}")
public class ${8:${5/^(.*)/$1RestController/}} {
@Autowired
private ${3:MyService} ${9:service};
@GetMapping
public ResponseEntity<List<$5>> getAll() {
return ResponseEntity.ok(${9:service}.findAll());
}
@GetMapping("/{id}")
public ResponseEntity<$5> getById(@PathVariable Long id) {
return ${9:service}.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<$5> create(@RequestBody $5 ${10:entity}) {
return ResponseEntity.status(HttpStatus.CREATED).body(${9:service}.save(${10:entity}));
}
@PutMapping("/{id}")
public ResponseEntity<$5> update(@PathVariable Long id, @RequestBody $5 ${9:entity}) {
return ${9:service}.update(id, ${9:entity})
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
boolean deleted = ${9:service}.delete(id);
return deleted ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
}
}