All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fi.evolver.basics.spring.http.crud.CrudController Maven / Gradle / Ivy

package fi.evolver.basics.spring.http.crud;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.http.HttpStatus;
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.ResponseStatus;

import fi.evolver.basics.spring.http.HttpInterceptor;
import fi.evolver.basics.spring.http.exception.HttpNotFoundException;
import fi.evolver.basics.spring.job.ResultState;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid;


/**
 * 

* An abstract REST like controller for JPA entity classes. * The entity class must have a Long type ID. *

* *

* Any concrete descendants of this class require the @RestController class * annotation to work correctly. Also, the entity class should have any unwanted methods * marked with the @JsonIgnore annotation. *

* * @param The entity class type. */ public abstract class CrudController extends ReadOnlyCrudController { /** * @param jpaRepository Repository for the entity class. */ protected CrudController(JpaRepository jpaRepository) { super(jpaRepository); } @Operation(summary = "Delete an entity by id") @ApiResponses(value = { @ApiResponse(responseCode = "204", description = "The entity was deleted successfully"), @ApiResponse(responseCode = "404", description = "The requested entity was not found"), @ApiResponse(responseCode = "500", description = "Internal server error") }) @PostMapping("/{id}/delete") @ResponseStatus(value = HttpStatus.NO_CONTENT) public void delete(@PathVariable long id) { HttpInterceptor.setMessageType(String.format("%s/delete", entityName)); try { jpaRepository.deleteById(id); jpaRepository.flush(); HttpInterceptor.setResultState(ResultState.ok("%s %s deleted", entityName, id)); } catch (EmptyResultDataAccessException e) { throw new HttpNotFoundException(); } } @Operation(summary = "Create a new entity or update an existing entity") @ApiResponses(value = { @ApiResponse(responseCode = "204", description = "The entity was created or updated successfully"), @ApiResponse(responseCode = "500", description = "Internal server error") }) @PostMapping @ResponseStatus(value = HttpStatus.NO_CONTENT) public void save(@RequestBody @Valid T entity) { HttpInterceptor.setMessageType(String.format("%s/save", entityName)); jpaRepository.saveAndFlush(entity); HttpInterceptor.setResultState(ResultState.ok("%s persisted", entityName)); } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy