What's the possible reason for this IllegalArgumentException?

svms54 :

I'm trying to update a value via PUT request. There seems to be an IllegalArgumentException/TypeMismatchException which I can't seem to figure out why.

Here's the Product model class:

@Table(name="product")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    private int price;
    private String vendor;
    private String description;
    private Boolean returnPolicy;

Here's the ProductController code for PUT method:

@Autowired
private ProductService productService;

@RequestMapping(method = RequestMethod.PUT, value = "/products/{id}")
public void updateProduct(@RequestBody Product product, @PathVariable int id) {
    res = productService.updateProduct(product, id);
    System.out.println(res ? "Successful" : "Unsuccessful");
}

Here's the updateProduct method for updating the product:

public Boolean updateProduct(Product product, int id) {
    if(productRepository.findById(Integer.toString(id)) != null) {
        productRepository.save(product);
        return true;
    }
        return false;
}

Here's my ProductRepository class:

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import testing.poc.models.Product;

@Repository
public interface ProductRepository extends CrudRepository<Product, String>{

}

This is the URL for my PUT request via Postman:

http://localhost:8080/products/8

This is the entry in the DB that I'm trying to update: entry

The message I'm getting is as follows:

{ "timestamp": "2019-03-27T13:53:58.093+0000", "status": 500, "error": "Internal Server Error", "message": "Provided id of the wrong type for class testing.models.Product. Expected: class java.lang.Integer, got class java.lang.String; nested exception is java.lang.IllegalArgumentException: Provided id of the wrong type for class testing.models.Product. Expected: class java.lang.Integer, got class java.lang.String", "path": "/products/8" }

and

org.hibernate.TypeMismatchException: Provided id of the wrong type for class testing.models.Product. Expected: class java.lang.Integer, got class java.lang.String

I don't understand how a String type is being supplied when I've declared 'id' as int everywhere. How can this be fixed?

hieinji :

Please let us see ProductRepository declaration, I assume findById method is wrong since it has a String as first parameter, but ProductRepository has Integer as @Id.

Change ProductRepository like below

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import testing.poc.models.Product;

@Repository
public interface ProductRepository extends CrudRepository<Product, Integer>{

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=129588&siteId=1