这个 IllegalArgumentException 的可能原因是什么?

What's the possible reason for this IllegalArgumentException?

我正在尝试通过 PUT 请求更新一个值。似乎有一个 IllegalArgumentException/TypeMismatchException,我似乎无法弄清楚为什么。

这是 产品 模型 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;

这是 PUT 方法的 ProductController 代码:

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

这里是更新产品的updateProduct方法:

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

这是我的 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>{

}

这是我通过 Postman 发出的 PUT 请求的URL:

http://localhost:8080/products/8

这是我要更新的数据库中的条目:

我收到的消息如下:

{ "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" }

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

当我在所有地方都将 'id' 声明为 int 时,我不明白如何提供 String 类型。如何解决?

请让我们看看 ProductRepository 声明,我假设 findById 方法是错误的,因为它有一个字符串作为第一个参数,但 ProductRepository 有整数作为 @Id。

改变ProductRepository如下

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

import testing.poc.models.Product;

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

}

将您的存储库更改为 CrudRepository<Product, Integer> ,第二个参数必须是实体 ID 的类型。