Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quadrixm/0af4a47613d22b4301ac47f4abb20db1 to your computer and use it in GitHub Desktop.
Save quadrixm/0af4a47613d22b4301ac47f4abb20db1 to your computer and use it in GitHub Desktop.
Custom Spring Boot Rest Controller Apache Velocity Template
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "") package ${PACKAGE_NAME};#end
#parse("File Header.java")
import com.litewit.liv.entities.${ENTITY};
import com.litewit.liv.exceptions.ResourceNotFoundException;
import com.litewit.liv.repositories.${ENTITY_REPO};
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(path="/${PATH}")
public class ${NAME} {
@Autowired
${ENTITY_REPO} ${ENTITY_LABEL}Repository;
// Get All ${ENTITY}
@GetMapping("/all")
public List<${ENTITY}> getAll${ENTITY}() {
return ${ENTITY_LABEL}Repository.findAll();
}
// Create a new ${ENTITY}
@PostMapping("/store")
public ${ENTITY} create${ENTITY}(@Valid @RequestBody ${ENTITY} ${ENTITY_LABEL}) {
return ${ENTITY_LABEL}Repository.save(${ENTITY_LABEL});
}
// Get a Single ${ENTITY}
@GetMapping("/get/{id}")
public ${ENTITY} get${ENTITY}ById(@PathVariable(value = "id") Long ${ENTITY_LABEL}Id) {
return ${ENTITY_LABEL}Repository.findById(${ENTITY_LABEL}Id)
.orElseThrow(() -> new ResourceNotFoundException("${ENTITY}", "id", ${ENTITY_LABEL}Id));
}
// Update a ${ENTITY}
@PutMapping("/update/{id}")
public ${ENTITY} update${ENTITY}(@PathVariable(value = "id") Long ${ENTITY_LABEL}Id,
@Valid @RequestBody ${ENTITY} ${ENTITY_LABEL}Details) {
${ENTITY} ${ENTITY_LABEL} = ${ENTITY_LABEL}Repository.findById(${ENTITY_LABEL}Id)
.orElseThrow(() -> new ResourceNotFoundException("${ENTITY}", "id", ${ENTITY_LABEL}Id));
// Customize base on entity fields
// ${ENTITY_LABEL}.setTitle(${ENTITY_LABEL}Details.getTitle());
// ${ENTITY_LABEL}.setContent(${ENTITY_LABEL}Details.getContent());
${ENTITY} updated${ENTITY} = ${ENTITY_LABEL}Repository.save(${ENTITY_LABEL});
return updated${ENTITY};
}
// Delete a ${ENTITY}
@DeleteMapping("/destroy/{id}")
public ResponseEntity<?> delete${ENTITY}(@PathVariable(value = "id") Long ${ENTITY_LABEL}Id) {
${ENTITY} ${ENTITY_LABEL} = ${ENTITY_LABEL}Repository.findById(${ENTITY_LABEL}Id)
.orElseThrow(() -> new ResourceNotFoundException("${ENTITY}", "id", ${ENTITY_LABEL}Id));
${ENTITY_LABEL}Repository.delete(${ENTITY_LABEL});
return ResponseEntity.ok().build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment