package de.gedoplan.seminar.jpa.exercise.rest; import java.util.List; import java.util.Optional; import org.slf4j.Logger; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; 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.RestController; import org.springframework.web.server.ResponseStatusException; import de.gedoplan.seminar.jpa.exercise.domain.Highway; import de.gedoplan.seminar.jpa.exercise.repository.HighwayRepository; @RestController @RequestMapping(path = "/highways", produces = MediaType.APPLICATION_JSON_VALUE) public class HighwayResource { private final HighwayRepository highwayRepository; private final Logger logger; public HighwayResource(HighwayRepository highwayRepository, Logger logger) { super(); this.highwayRepository = highwayRepository; this.logger = logger; } /** * Exercise JPA_BASICS_01: Insert test data. */ @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) public void insert(@RequestBody Highway highway) { this.logger.debug("----- insert -----"); this.highwayRepository.save(highway); this.logger.debug("Inserted: " + highway); } /** * Exercise JPA_BASICS_01: Find entries by id. */ @GetMapping("/{ID}") public Highway findById(@PathVariable("ID") Integer id) { this.logger.debug("----- findById -----"); Optional highway = this.highwayRepository.findById(id); highway.ifPresent(h -> this.logger.debug(id+": "+h)); return highway.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); } /** * Exercise JPA_BASICS_03: Find entries by origin. */ @GetMapping("/findByOrigin/{origin}") public List findByOrigin(@PathVariable("origin") String origin) { this.logger.debug("----- findByOrigin -----"); List highways = this.highwayRepository.findByOrigin(origin); this.logger.debug(origin+": "+highways); return highways; } @GetMapping("/countOrigins") public Long findByOrigin() { this.logger.debug("----- countOrigins -----"); Long count = this.highwayRepository.countOrigins(); this.logger.debug("Count distinct Origins: "+count); return count; } }