1

My springboot model is this:

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    @Document(collection = "products")
    public class Product {
        @Id
        private String id;
        @NotEmpty(message = "name is mandatory")
        private String name;
        @NotEmpty(message = "price is mandatory")
        private int price;
        private MultipartFile file;
    }

    @AllArgsConstructor
    @Data
    @Builder
    public class AddProductCommand implements Serializable {
        @TargetAggregateIdentifier
        private String id;
        @NotNull(message = "no product details were supplied")
        @Valid
        private Product product;
    
        public AddProductCommand(){
    
        }
    }

Since I have to send a MultipartFile from the reactjs, I must use FormData. I have tried the following:

    async handleSubmit(event) {

    event.preventDefault();
    try {
        let product = new FormData();    
        product.append("name", this.state.name);
        product.append("price", this.state.price);
        product.append("file", this.state.file);
        let addProductCommand = new FormData();
        addProductCommand.append("product", product);
        const response = await axios.post(SELL_URL, addProductCommand , {
                headers: {
                'Content-Type': 'multipart/form-data'
              }
          });
        this.clearState();
        event.target.reset();
        this.props.history.push("/buy"); 
    } catch (err) {
       console.log(JSON.stringify(err));
    }

    }

However, I got following error in the springboot:

DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'addProductCommand' on field 'product': rejected value [[object FormData]]; codes [typeMismatch.addProductCommand.product,typeMismatch.product,typeMismatch.com.cognizant.user.core.models.Product,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [addProductCommand.product,product]; arguments []; default message [product]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.cognizant.user.core.models.Product' for property 'product'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.cognizant.user.core.models.Product' for property 'product': no matching editors or conversion strategy found]]

What have I missed and how should I fix this error?

Add controller code. I am trying to implement it as CQRS design. Here is the controller. I nedd to write more description not much code. Otherwise stackoverflow doesn't allow me do add more code :(.

@RestController
@RequestMapping(path = "/api/v1/addProduct")
public class AddProductController {
    private final CommandGateway commandGateway;


 @Autowired
  public AddProductController(CommandGateway commandGateway) {
    this.commandGateway = commandGateway;
 
}

@PostMapping
public ResponseEntity<AddProductResponse> registerUser(@Valid @ModelAttribute AddProductCommand command) {
    var id = UUID.randomUUID().toString();
    command.setId(id);

    try {
        commandGateway.sendAndWait(command);
        return new ResponseEntity<>(new AddProductResponse(id, "Product added successfully!"), HttpStatus.CREATED);
    } catch (Exception e) {
        var safeErrorMessage = "Error while processing add product request for id - " + id;
        System.out.println(e);

        return new ResponseEntity<>(new AddProductResponse(id, safeErrorMessage), HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

 }
5
  • share your controller method also Commented Jun 5, 2022 at 12:32
  • Ths for your response. Pls check controller code. Commented Jun 5, 2022 at 12:40
  • can you try adding @ModelAttribute("product") to your controller Commented Jun 5, 2022 at 14:42
  • 2
    Thx @ModelAttribute("product") solved the problem. If u wish to give it as an answer, pls do it. Commented Jun 6, 2022 at 16:49
  • nice :) sure I will add it as the answer. Commented Jun 6, 2022 at 19:01

1 Answer 1

2

for the above scenario, you are appending form data to the product key addProductCommand.append("product", product); so in your controller, you should get the product entity. add this to your controller; @ModelAttribute("product")

public ResponseEntity<AddProductResponse> registerUser(@Valid @ModelAttribute("product") AddProductCommand command)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.