Category.java
@Entity
@Data
@Table(name = "categories")
public class Category implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Size(min = 5, max = 60)
@Column(name = "category", length = 50, unique = true)
private String category;
@OneToMany
private Set<Product> product;
}
分类控制器.java
@GetMapping("/category/{id}")
public ResponseEntity<List<Product>> getCategoryById(@PathVariable(value = "id") Long categoryId) {
List<Product> category = productRepository.findAllByCategoryId(categoryId);
if (category == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok().body(category);
}
ControllerRepositoy.java
@Repository
public interface CategoryRepository extends JpaRepository<Category,Long>{
}
Products.Java
@Entity
@Data
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Size(min = 5, max = 60)
@Column(name = "productName", length = 50, unique = true, nullable = false)
private String productName;
@NotNull
@Size(min = 10, max = 200)
@Column(name = "description", length = 200, unique = true, nullable = false)
private String description;
@NotNull
//@Pattern(regexp = "^[0-9]*$")
@Size(min = 1, max = 10)
@Column(name = "price", length = 10, unique = true, nullable = false)
private int price;
@ManyToOne
@JoinColumn(name="product")
private Category categoryId;
@NotNull
@Column(name = "imageURL", length = 500, nullable = false)
private String image;
}
ProductController.java
@RestController
@RequestMapping("/product")
public class ProductController {
@Autowired
ProductRepository productRepository;
@GetMapping("/product")
public List<Product> getAllNotes() {
return productRepository.findAll();
}
@GetMapping("/product/{id}")
public ResponseEntity<Optional<Product>> getProductById(@PathVariable(value = "id") Long categoryID) {
Optional<Product> product = productRepository.findById(categoryID);
if(product == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok().body(product);
}
@PostMapping("/product")
public @Valid Product createProduct(@Valid @RequestBody Product product) {
System.err.println(product);
return productRepository.save(product);
}
}
我希望能够使用类别ID查询产品。因此,我在categoryController中使用了productRepository。
这是代码。当给定Id进行GET请求时,会显示一个错误。该错误为:
java.lang.IllegalArgumentException: Parameter value [1] did not match expected type [com.susl.Agroapi.model.Category (n/a)]
如何解决这个问题?
ProductRepository
的实例,对吗? - MakotoproductRepository
类是什么?它必须是ProductRepository
接口。 - Bogdan Oros