【问题标题】:Hibernate GetbyID : java.lang.NoSuchMethodException Entity errorHibernate GetbyID:java.lang.NoSuchMethodException 实体错误
【发布时间】:2023-01-19 01:04:31
【问题描述】:

Hibernate 并尝试构建简单的功能,我们可以通过 Id 搜索产品。 Hibernate 具有 inbuit 函数来通过其 id 搜索实体。我尝试了同样的方法,但我收到了“java.lang.NoSuchMethodException”。

MyController.java :

 @GetMapping(value = "/getProducts/{id}" , produces ="application/json")
    public ResponseEntity<Product> display(@PathVariable int id) {
        Product products = productServiceImp.getAllProducts(id);
        return ResponseEntity.ok(products);

MyProductServiceImp:

@Override
    public Product getAllProducts(int product_id ) {
        return productRepository.getById(product_id );
    }

MyProductRepository:
@Repository
public interface ProductRepository extends JpaRepository<Product, Integer> {
}

Schema of Product table : (product_id, desciption,display_name, qty, amount)

当我尝试通过邮递员调用 API 时 curl --location --request GET 'http://localhost:8080/admin/getProducts/1. 我看到它是由以下原因引起的:java.lang.NoSuchMethodException: com.Project.OrderProcessing.OrderProcessing.Entity.Product$HibernateProxy$zAdAYVvM.&lt;init&gt;().I am unable to understand reason behind it

【问题讨论】:

  • 你为什么打电话给/Admin/getProducts/1而不只是/getProducts/1
  • OP 可以在课堂上为 /admin 提供 @RequestMapping

标签: java hibernate rest


【解决方案1】:

试试findById,因为getById 已被弃用。未经测试,但类似于:

我的产品服务展示:

@Override
public Optional<Product> findById(Integer productId) {
    return productRepository.findById(productId);
}

产品.java

@Entity //make sure this is present
@Getter //from Lombok
@Setter //from Lombok
public class Product {

@Id //need this
@GeneratedValue //need this to auto-generate
private Integer id;

private String description;

//the rest: displayName, quantity, amount...

}

您的 @Repository 界面看起来不错。根据您需要执行的操作,您的控制器有不同的变体。但现在,只需尝试调用您的服务方法,这样您就知道您从数据库中获取了结果并从那里开始工作。

Camel-case 你的变量通常是为了保持一致性。然后您可以在存储库的接口中使用 Spring 约定,这样您的方法就可以看起来像 findAllByDisplayName() 而不是 findAllByDisplay_Name(),Spring 将为您处理查询。

另请注意,您可能不会获得具有一个产品 ID 的所有产品,对吗?所以它应该被称为getProductfindProductgetProductByIdfindProductById

【讨论】:

    【解决方案2】:
    MyControllerClass:
    @RequestMapping("/admin")
    @RestController
    public class ProductController {
     @GetMapping(value = "/getProducts/{id}" , produces ="application/json")
        public Optional<Product> display(@PathVariable int id) {
            Optional<Product> products = productServiceImp.getProductDetailsbyID(id);
            return products;
    }
    }
    MyProductServiceImp :
    @Override
        public Optional<Product> getProductDetailsbyID(int product_id ) {
            Optional<Product> prodresult=productRepository.findById(product_id);
            return prodresult;
        }
    

    我用 FindbyID 代替了 GetById,它起作用了!!

    【讨论】:

      猜你喜欢
      • 2015-10-28
      • 1970-01-01
      • 2023-03-29
      • 2016-09-06
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 2019-11-17
      • 2016-10-09
      相关资源
      最近更新 更多