Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@

import com.example.demo.entity.Position;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.Optional;


public interface PositionRepository extends JpaRepository<Position,Integer> {
@Query(value = "SELECT p FROM Position p WHERE p.name = :name")
Optional<Position> findByName(@Param("name") String name);
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.util.List;
import java.util.Optional;

@Component
@AllArgsConstructor
Expand All @@ -38,6 +40,10 @@ public ResponseEntity<?> getAll(Integer page, Integer size) {
}

public ResponseEntity<?> save(PositionDto dto) {
Optional<Position> existingName = positionService.getByName(dto.getName());
if (existingName.isPresent()) {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
Position position = positionMapper.toEntity(dto);
positionService.save(position);
PositionDto positionDto = positionMapper.toDto(position);
Expand All @@ -47,6 +53,10 @@ public ResponseEntity<?> save(PositionDto dto) {
public ResponseEntity<?> update(Integer id, PositionDto dto){
Position position = positionService.getById(id).
orElseThrow(() -> new ResourceNotFoundException(Position.class.getSimpleName(), id));
Optional<Position> existingName = positionService.getByName(dto.getName());
if (existingName.isPresent() && existingName.get().getId().equals(id)) {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
positionMapper.updateEntityFromDto(dto, position);
positionService.update(position);
return ResponseEntity.ok().build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,8 @@ public void delete(Position position) {
public Optional<Position> getById(Integer id) {
return positionRepository.findById(id);
}

public Optional<Position> getByName(String name) {
return positionRepository.findByName(name);
}
}