Spring Boot通过Id请求数据

4

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)]

如何解决这个问题?

2
你正在使用ProductRepository的实例,对吗? - Makoto
1
当询问异常时,请发布相关代码(ProductRepository和Product),以及完整的异常堆栈跟踪。请注意,返回列表的存储库方法将始终返回列表。永远不会是null。 - JB Nizet
你在代码中使用的productRepository类是什么?它必须是ProductRepository接口。 - Bogdan Oros
3个回答

1
你需要像下面这样更改代码:
将产品实体添加到
@ManyToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
private Category category;

添加“分类”实体到:
@OneToMany(mappedBy="category",cascade=CascadeType.REMOVE)
private Set<Product> pr;

制作如下所示的产品存储库:
public interface ProductRepository extends PagingAndSortingRepository<Product, Long>{
    List<Product> findAllProductByCategoryId(@Param("id")Long id);
}

然后您可以通过使用ProductRepository调用Controller类中的findAllProductByCategoryId({categoryId})


0

你还没有发布所请求的ProductRepository,但现在我们至少有了Product实体,错误很可能是方法应该被命名为

findAllByCategoryIdId

由于您想要按字段 categoryIdid 进行搜索。

或者您可以(也应该)将字段 categoryId 重命名为 category,因为它代表的是一个类别,而不是一个 ID。


-1

看起来你想使用CategoryRepository,但却使用了ProductRepository。

创建:

 @Autowired
 CategoryRepository categoryRepository;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接