Error : java.lang.IllegalArgumentException: The given id must not be null! - Spring Boot , Mysql

Viewed 1620

I got this error when inserting data into the sample_category table by the client-side. This is my controller method.

@PostMapping("/request")
    public SampleRequest createRequest(@Valid @RequestBody SampleRequest sampleRequest) throws ResourceNotFoundException{

        User user = userRepository.findById(sampleRequest.getUser().getId())
                .orElseThrow(() -> new ResourceNotFoundException("User Not Found"));

        Category category = categoryRepository.findById(sampleRequest.getCategory().getId())
                .orElseThrow(()-> new ResourceNotFoundException("Category Not Found"));

        sampleRequest.setUser(user);
        sampleRequest.setCategory(category);

        return sampleRequestRepository.save(sampleRequest);

    }

And this is the Model class.

@Entity
@Table(name = "sample_requests")
public class SampleRequest extends DateAudit {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    private String title;


    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "user_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private User user;

    @ManyToOne(fetch = FetchType.LAZY,optional = false)
    @JoinColumn(name = "category_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Category category;


    private String description;

    private Boolean approved;

    @NotNull
    private Long quantity;

// Getters and setters

and this is the client-side request.

{
    "id" : "1",
    "title" : "Test Title",
    "user": {
        "user" : 7
    },
    "category": {
        "category" : 1
    },
    "description" : "test description",
    "quantity" : "2"
    
}

I need to add new sample request.

1 Answers

In you JSON you are not sending id in id node. That's why user and category object's id is null.

And findById accept only not null id else throw execption(Ref). JSON should be like

{
    ...
    "user": {
        "id" : 7
    },
    "category": {
        "id" : 1
    }
}
Related