Home > Blockchain >  (com.example.shonicserver.model.Product is in unnamed module of loader 'app'; java.util.Li
(com.example.shonicserver.model.Product is in unnamed module of loader 'app'; java.util.Li

Time:06-18

I get an error when I want return ProductByid. How to solve this error?

Model class

public class Product {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;

@Column(name = "name",  unique = true)
private String name;

@Column(name = "price" )
private Integer price;

@Column(name = "qty",  length = 3)
private Integer qty;

@Column(name = "date")
private String date;


@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "category_id")
private Categories categories;


@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "brand_id")
private Brand brand;

@OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<FlashSale> discount;

@Column(name = "image")
private String image;

@Column(name = "image_full")
private Boolean imageFull;

@OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Rating> ratingList;

Controller class

@GetMapping("getById/{id}")
public ResponseEntity<Response> getOneProduct(@PathVariable UUID id) {
    List<Product> product=this.productService.findById(id);
    return new ResponseEntity<>(new Response(201,"succsess",product,null),HttpStatus.OK);
}

ServiceImpl class

public List<Product> findById(UUID id) {
  Optional<Product> optionalProduct = productRepository.findById(id);
    Product product;
     if(optionalProduct.isPresent()) {
        product=optionalProduct.get();
        return (List<Product>) product;
        } else {
           return null;
        }

}

error 2022-06-18 06:57:19.170 ERROR 9988 --- [nio-8080-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: class com.example.shonicserver.model.Product cannot be cast to class java.util.List (com.example.shonicserver.model.Product is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')] with root cause java.lang.ClassCastException: class com.example.shonicserver.model.Product cannot be cast to class java.util.List (com.example.shonicserver.model.Product is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')

CodePudding user response:

Since your Product Id is UUID, then every product will have unique Id. So as per the given error says, findById only return one product entity, but you try to get List<Product>. you can't cast product into List as in your code.

There are 2 ways to fix this.

  1. Change the return type of findById(UUID id) from List<Product> to Product since productRepository.findById(id) only return one Optional<Product>.

    // Controller
    @GetMapping("getById/{id}")
    public ResponseEntity<Response> getOneProduct(@PathVariable UUID id) {
    Product product=this.productService.findById(id);
    return new ResponseEntity<>(new Response(201,"succsess",product,null),HttpStatus.OK);
    }
    
    // ServiceImpl class
    public Product findById(UUID id) {
    Optional<Product> optionalProduct = productRepository.findById(id);
     if(optionalProduct.isPresent()) {
        return optionalProduct.get();
    
        } else {
           return null;
        }
    
    }
    
  2. Second way is if you want to return the Product as a list then convert the optionalProduct you get in the service into List and return that list.

    public List<Product> findById(UUID id) {
        Optional<Product> optionalProduct = productRepository.findById(id);
         if(optionalProduct.isPresent()) {
            Product pr = optionalProduct.get();
            // Add Product to list and return that list.
            return Stream.of(pr).collect(Collectors.toList())
            } else {
               return null;
            }
    
        }
    

Hope this will solve your problem.

CodePudding user response:

you have not shared your ProductRepository here and it is just a guess based on your error log.

It seems that you have something like this in your repository class:

Optional<List<Product>> findById(UUID id);

But in your service layer you are trying to fetch data like this:

Optional<Product> optionalProduct = productRepository.findById(id);

And because you are using UUID I think that it is impossible to expect a List<Product> and you will only expect a single Product, so what you need to do is only changing your method in your repository layer to :

Optional<Product> findById(UUID id);
  • Related