I am making my put method in my controller class but I have a a lot of different attributes I want to set is there somesort of plugin i can use to fill in all my setters
@PutMapping(path = "{documentId}")
public ResponseEntity<Document> updateDocument(
@PathVariable(value = "documentId") String documentId,
@Validated @RequestBody Document documentDetails) throws ResourceNotFoundException {
Document document = documentRepo.findById(documentId)
.orElseThrow(() -> new ResourceNotFoundException("Document not found on :: " documentId));
document.setTitle(documentDetails.getTitle());
final Document updateDocument = documentRepo.save(document);
return ResponseEntity.ok(updateDocument);
}
CodePudding user response:
You are probably looking for Lombok. Basically, you can add an annotation to your class and Lombok generates setters and other stuff for you.
CodePudding user response:
Since Both classes have the same property names, this spring util would save you a ton of time;
BeanUtils.copyProperties(source, target);
So you'll have this instead:
@PutMapping(path = "{documentId}")
public ResponseEntity<Document> updateDocument(
@PathVariable(value = "documentId") String documentId,
@Validated @RequestBody Document documentDetails) throws ResourceNotFoundException {
Document document = documentRepo.findById(documentId)
.orElseThrow(() -> new ResourceNotFoundException("Document not found on :: " documentId));
BeanUtils.copyProperties(documentDetails, document);
// You can also ignore a particular property or properties
// BeanUtils.copyProperties(documentDetails, document, "id");
final Document updateDocument = documentRepo.save(document);
return ResponseEntity.ok(updateDocument);
}
CodePudding user response:
You could use Mapstruct to create mappings for this case.
package com.example.demo;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
@Mapper(componentModel = "spring")
public interface DocumentMapper {
void updateDocument(@MappingTarget Document target, Document source);
}
and then use it in your controller.
@RestController
@RequiredArgsConstructor
public class DocumentController {
private final DocumentMapper documentMapper;
@PutMapping
public Document updateDocument(@RequestBody final Document documentDetails) {
Document document = new Document(); // documentRepo.findById
documentMapper.updateDocument(document, documentDetails);
// documentRepo.save(document)
return document;
}
}