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

标签 java spring illegalargumentexception type-mismatch

我正在尝试通过 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:

http://localhost:8080/products/8

这是我尝试更新的数据库中的条目: entry

我收到的消息如下:

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

相关文章:

java - Spring批处理读取多条记录并处理多条记录

Spring Post Controller重定向仅打印url而不是重定向

java - 为什么我的代码忽略异常?

java - 如何将两个链表相乘成第三个链表?

java - 如何从 Scala 调用 Java 接口(interface)的 T eq(Object) 方法?

java - 将数据写入 StdData 文件中的智能卡

java - 如何在 JTextField 上设置焦点?

spring - 使用 spring 社交的长生命周期访问 token

java - Spring Solr 存储库

java-如何执行 SQL 注入(inject)以进行测试?