Enrique GF
Enrique GF

Reputation: 1295

Error of java.lang.NumberFormatException: For input string in fetch to plain endpoint

Hello developers i have tried to deal with this but can't find a logical solution. Im doing this app with microservices, where the most important items(renters, products,rents ) are each one a microservice. Due to that and its dependency on each other , also i created a common library where in the reusing of tables needed by several app components is its main function.As database im using mySQL. In one of the microservices controllers im receiving this error over the endpoint of fetching all products:

    org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String]
 to type [java.lang.Long] for value 'all'; nested exception is java.lang.NumberFormatException: For input
 string: "all"

The cause of this error is in the controller of products referring to this:

package com.microproducts.controllers;
 
 
import com.commons.dtos.ProductsDtos;
import com.commons.entities.Product;
import com.microproducts.exceptions.GeneralException;
import com.microproducts.exceptions.NotFoundException;
import com.microproducts.responses.AppResponse;
import com.microproducts.services.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
 
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
@RestController
public class ProductController {
    @Autowired
    ProductService productService;
 
    @Autowired
    ProductsDtos productsDtos;
 
 @GetMapping("/products/all")==============================>APARENTLY HERE
    public List<Product> getAllProducts() {
       List<Product> allProducts = productService.getAllProducts().stream().collect(Collectors.toList());
        return allProducts;
    }
 
}

 

NOTE:I have put as alternatives and neither work

 @GetMapping(value="/products/all")
...
 @GetMapping(path="/products/all")
...
 @ResponseStatus(HttpStatus.OK)
 @RequestMapping(value = "/products/all", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
...
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
@RequestMapping(value = "products/all", method = RequestMethod.GET)

As you can see in this endpoint i don't pass a parameter or something which might cause a weird behave , thus still can't figure it out.

then my service and implementation packages referring to this process got the following structure:

SERVICE
package com.microproducts.services;
import com.commons.entities.Product;
import java.util.List;
import java.util.Map;
 
public interface ProductService {
 
    List<Product> getAllProducts();
 
}
 
 
 
SRVICE IMPLEMENTACION
package com.microproducts.servicesImpl;
 
import com.commons.dtos.ProductsDtos;
import com.commons.entities.Product;
import com.microproducts.exceptions.GeneralException;
import com.microproducts.exceptions.NotFoundException;
import com.microproducts.repositories.ProductRepository;
import com.microproducts.services.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
 
@Service
public class ProductServiceImpl implements ProductService {
 
    @Autowired
    ProductRepository productRepository;
 
    @Autowired
    ProductsDtos productsDtos;
 
       @Override
    @Transactional(readOnly = true)
    public List<Product> getAllProducts() {
        List<Product> productsList = productRepository.findAll();
       return productsList;
    }
 }

Repository and Entity of Product is designed in this way :

package com.microproducts.repositories;
 
import com.commons.entities.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
 
import java.util.List;
import java.util.Optional;
 
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    
}

In this case as Product entity is a reusable for other microservices i shared it in a package titled commons

package com.commons.entities;
 
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
 
@Entity
@Table(name="PRODUCT")
public class Product implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    Long id;
 
    @Column(name="PRODUCT_NAME")
    private String productName;
 
    @OneToMany(fetch=FetchType.LAZY,mappedBy = "product")
    private Set<Rent> listRentsInProduct=new HashSet<>();
 
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="RENTER_ID",nullable = false)
    private Renter renter;
 
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="PRODUCT_TYPE_ID",nullable = false)
    private ProductType productType;
 
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="PRODUCT_PRICE_ID",nullable = false)
    private ProductPrice productPrice;
 
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="PRODUCT_SUBTYPE_ID",nullable = false)
    private ProductSubType productSubType;
 
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="PRODUCT_INVENTARY_ID",nullable = false)
    private ProductInventary productInventary;
 
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="PRODUCT_FEE_DELAY_ID",nullable = false)
    private ProductFeeDelay productFeeDelay;
 
    private static final long serialVersionUID=1285454306356845809L;
 
    /////////////////////////////constructor////////////////////////////
    public Product(){};
    public Product(Long id, String productName,
//                   Set<Rent> listRentsInProduct,
                   Renter renter, ProductType productType,ProductPrice productPrice,
                   ProductSubType productSubType, ProductInventary productInventary,
                   ProductFeeDelay productFeeDelay) {
        this.id = id;
        this.productName = productName;
        this.listRentsInProduct = listRentsInProduct;
        this.renter = renter;
        this.productType = productType;
        this.productPrice = productPrice;
        this.productSubType = productSubType;
        this.productInventary = productInventary;
        this.productFeeDelay = productFeeDelay;
 
    }
 
    /////////////////////////other methods/////////////////////////////////
    public void addRent(Rent rent){
        listRentsInProduct.add(rent);
    }
    public Set<Rent>getAllRentsOfUser(){return listRentsInProduct;}
 
    ///////////////////////////getters and setters////////////////////////////////////
    public Long getId() {  return id; }
    public void setId(Long id) {  this.id = id; }
 
    public String getProductName() {  return productName;}
    public void setProductName(String productName) {  this.productName = productName;}
 
    public Set<Rent> getListRentsInProduct() {  return listRentsInProduct; }
    public void setListRentsInProduct(Set<Rent> listRentsInProduct) { this.listRentsInProduct = listRentsInProduct; }
 
    public Renter getRenter() { return renter;}
    public void setRenter(Renter renter) {   this.renter = renter; }
 
    public ProductType getProductType() {   return productType; }
    public void setProductType(ProductType productType) {    this.productType = productType; }
 
    public ProductPrice getProductPrice() {   return productPrice;}
    public void setProductPrice(ProductPrice productPrice) {   this.productPrice = productPrice;}
 
    public ProductSubType getProductSubType() {    return productSubType;}
    public void setProductSubType(ProductSubType productSubType) {   this.productSubType = productSubType;}
 
    public ProductInventary getProductInventary() {   return productInventary;}
    public void setProductInventary(ProductInventary productInventary) {    this.productInventary = productInventary;}
 
    public ProductFeeDelay getProductFeeDelay() { return productFeeDelay; }
    public void setProductFeeDelay(ProductFeeDelay productFeeDelay) { this.productFeeDelay = productFeeDelay; }
 
    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", productName='" + productName + '\'' +
                ", listRentsInProduct=" + listRentsInProduct +
                ", renter=" + renter +
                ", productType=" + productType +
                ", productPrice=" + productPrice +
                ", productSubType=" + productSubType +
                ", productInventary=" + productInventary +
                ", productFeeDelay=" + productFeeDelay +
                '}';
    }
}

And the Spring app configuration with the scan of all shareable components and entities gets exposed in this way:

package com.microproducts;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
 
@SpringBootApplication
@ComponentScan({"com.commons.dtos","com.commons.entities","com.commons.exceptions","com.commons.responses"})
@EntityScan("com.commons.entities")
public class MicroproductsApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(MicroproductsApplication.class, args);
    }
 
}


despite of having the problem on that url of my controller i wanted to expose part of the code cause perhaps my structure isn't correct or i'm omitting something which collaterally might caused the error. But is quite rare that trying to fetch my data that mistake over that plain url string shows up cause of sort kind of background process pretending to mute the string or part of it to Long. Any help, or opinion about which would be the path toward the solutions is great!!!! Thanks in advance!!!.

By the way my pom for this microservice would be :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.microproducts</groupId>
    <artifactId>microproducts</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>microproducts</name>
    <description>Demo project for microproducts</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
    </properties>

    <dependencies>
        <!--        LIBRERIA COMUN-->
        <dependency>
            <groupId>com.commons</groupId>
            <artifactId>commons</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

And a more extended log of the error through the console is as follows:


org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'all'; nested exception is java.lang.NumberFormatException: For input string: "all"
    at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:47) ~[spring-core-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:192) ~[spring-core-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:175) ~[spring-core-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.data.repository.support.ReflectionRepositoryInvoker.convertId(ReflectionRepositoryInvoker.java:293) ~[spring-data-commons-2.3.6.RELEASE.jar:2.3.6.RELEASE]
    at org.springframework.data.repository.support.ReflectionRepositoryInvoker.invokeFindById(ReflectionRepositoryInvoker.java:145) ~[spring-data-commons-2.3.6.RELEASE.jar:2.3.6.RELEASE]
    at org.springframework.data.repository.support.CrudRepositoryInvoker.invokeFindById(CrudRepositoryInvoker.java:92) ~[spring-data-commons-2.3.6.RELEASE.jar:2.3.6.RELEASE]
    at org.springframework.data.rest.core.support.UnwrappingRepositoryInvokerFactory$UnwrappingRepositoryInvoker.invokeFindById(UnwrappingRepositoryInvokerFactory.java:94) ~[spring-data-rest-core-3.3.6.RELEASE.jar:3.3.6.RELEASE]
    at org.springframework.data.rest.webmvc.RepositoryEntityController.getItemResource(RepositoryEntityController.java:514) ~[spring-data-rest-webmvc-3.3.6.RELEASE.jar:3.3.6.RELEASE]
    at org.springframework.data.rest.webmvc.RepositoryEntityController.getItemResource(RepositoryEntityController.java:327) ~[spring-data-rest-webmvc-3.3.6.RELEASE.jar:3.3.6.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_221]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_221]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_221]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_221]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) [spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) [spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) [tomcat-embed-core-9.0.41.jar:4.0.FR]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) [spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) [tomcat-embed-core-9.0.41.jar:4.0.FR]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) [spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) [spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_221]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_221]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.41.jar:9.0.41]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_221]
Caused by: java.lang.NumberFormatException: For input string: "all"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_221]
    at java.lang.Long.parseLong(Long.java:589) ~[na:1.8.0_221]
    at java.lang.Long.valueOf(Long.java:803) ~[na:1.8.0_221]
    at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:214) ~[spring-core-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.core.convert.support.StringToNumberConverterFactory$StringToNumber.convert(StringToNumberConverterFactory.java:64) ~[spring-core-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.core.convert.support.StringToNumberConverterFactory$StringToNumber.convert(StringToNumberConverterFactory.java:50) ~[spring-core-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService$ConverterFactoryAdapter.convert(GenericConversionService.java:437) ~[spring-core-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:41) ~[spring-core-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    ... 58 common frames omitted

2020-12-19 10:42:06.389  WARN 7180 --- [nio-9000-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'all'; nested exception is java.lang.NumberFormatException: For input string: "all"]

And this is a preliminar view of my database schema and the table of products enter image description here

Upvotes: 1

Views: 6341

Answers (3)

mentallurg
mentallurg

Reputation: 5207

  1. You are using the same table in different microservices. This is an indicator that your microservices are incorrectly defined. I suggest you revise your data model, check what data belong to one domain, what belong to different domains. And only then define services. Then may be you will see that 2 or even all 3 current microservices should actually be a single microservice. Then check how persistence works.

  2. The call CrudRepositoryInvoker.invokeFindById() means there was repository method findById() called. We don't see the whole code of the controller class. But I suppose there are actually 2 methods:

@GetMapping("/products/all")
public List<Product> getAllProducts() {
    ...

@GetMapping("/products/{id}")
public List<Product> getProductById(@PathVariable("id") Long id) {
    ...

When one calls /products/all, Spring considers it as a call of /products/{id} and attempts to convert all to a Long value. As a result we see the stack trace shows in the OP.

What is the reason? The reason is bad design. The method /products/all makes the whole service not REST-ful.

Solution? Here it is:

@GetMapping("/products")
public List<Product> getAllProducts() {
    ...

Upvotes: 2

Igor Bljahhin
Igor Bljahhin

Reputation: 987

Apparently, you have spring-boot-starter-data-rest activated in your project. With this library rest controllers magically get a special "meanings" and your endpoint /products/all means now "return product with ID "all". Just remove this dependency from pom.xml, I guess you do not need it.

Upvotes: 0

HariKishore
HariKishore

Reputation: 169

Please add the alternative in controller and give it a try.

@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
@RequestMapping(value = "products/all", method = RequestMethod.GET)
public List<Product> getAllProducts(HttpServletRequest request, HttpServletResponse response) {
   List<Product> allProducts = productService.getAllProducts().stream().collect(Collectors.toList());
    return allProducts;
}

I think you don't to add findAll() in JPA Repository as it have a default. you can comment it.

Upvotes: 0

Related Questions