Reputation: 129
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:
This is the entry in the DB that I'm trying to update:
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?
Upvotes: 2
Views: 914
Reputation: 42
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>{
}
Upvotes: 2
Reputation: 17534
Change your repository to a CrudRepository<Product, Integer>
, the second parameter must be the type of the ID of the entity.
Upvotes: 2