我正在尝试通过 PUT 请求更新值。似乎有一个 IllegalArgumentException/TypeMismatchException 我似乎无法弄清楚为什么。
这是产品模型类:
@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 类:
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:
这是我尝试更新的数据库中的条目:
我收到的消息如下:
{ "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
方法是错误的,因为它有一个 String 作为第一个参数,但 ProductRepository
有 Integer作为@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>{
}
关于java - 这个 IllegalArgumentException 的可能原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55379669/