简体   繁体   中英

adding setters to java spring boot controller class

I am making my put method in my controller class but I have aa 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);
}

You are probably looking for Lombok. Basically, you can add an annotation to your class and Lombok generates setters and other stuff for you.

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;
    }
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM