No value present java ошибка

Есть поиск в коллекции:

for (Object dataRow : objects) {
    AttributeModel attribute = document.getAttributeModels().stream()
    .filter(atr -> atr.getName().equals(nameField)).findFirst().get();
....
....
}

но если элемента с таким именем нету в коллекции, вы,выбрасывает ошибку :

Exception in thread «main» java.util.NoSuchElementException: No value
present

Как правильно обработать эту ошибку в стриме?
И как можно сделать, чтобы при отсутствии элемента, выполнялся следующий цикл for() ?

Ростислав Красный's user avatar

задан 6 окт 2018 в 9:24

Леонид Дубравский's user avatar

Используйте метод Optional.get() только после проверки Optional.isPresent()

for (Object dataRow : objects) {
    Optional<AttributeModel> opt = document.getAttributeModels()
    .stream()
    .filter(atr -> atr.getName().equals(nameField))
    .findFirst();
    if (opt.isPresent()){
      AttributeModel attribute = opt.get();
    } 
....
....
}

ответ дан 6 окт 2018 в 9:31

Vlad Mamaev's user avatar

Vlad MamaevVlad Mamaev

7313 серебряных знака7 бронзовых знаков

1

In this tutorial, Learn how to fix java.util.NoSuchElementException: No value present error in java application.

This error java.util.NoSuchElementException: No value present thrown when there is no element found in Optional object with Stream API in java8.

Let’s create an array and initialize it with string values. You can check how to create and initialize an array in a single line

Let’s see a simple example to check if a string exists in an array.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<String> srs = new ArrayList<>(Arrays.asList("One", "two", "three"));
        String str=srs.stream().filter(e->e.equals("ten")).findFirst().get();


    }
}

It throws an error Exception in thread “main” java.util.NoSuchElementException: No value present

Exception in thread "main" java.util.NoSuchElementException: No value present
    at java.util.Optional.get(Optional.java:135)
    at Test.main(Test.java:8)

Let’s understand the above code.

  • Iterated an array using stream API in java8, Stream is another way to iterate the enumerated object to improve performance
  • It returns the Stream object using the stream() method
  • Calling filter method on stream which matched with a given predicate for each element and returns matched values with stream
  • Calling the first element using findFirst from the matched stream and returns Optional class
  • if optional Object is empty, get method return no value present error
    i.e Optional.get() method gives java.util.NoSuchElementException when Optional object is empty

Here is a get method implemented in java8

 public T get() {
        if (value == null) {
            throw new NoSuchElementException("No value present");
        }
        return value;
    }

There are multiple ways we can fix to check for the optional object is empty or not.

Let’s see some other simple examples to reproduce and solution for this error

Optional<Integer> number1  =  Optional.of(123);
Optional<Integer> number2  =  Optional.empty();
System.out.println(number1.get()); // 123
System.out.println(number2.get()); // Exception in thread "main" java.util.NoSuchElementException: No value present

One way,

We can check Optional empty or not using isPresent() method in Optional class

        if (number2.isPresent()){
            System.out.println(number2.get());
    }else{
            System.out.println("number2 is an empty");
        }

isPresent()method returns true if value exists, else return false.

Thus, we can avoid an error.

Another way using the orElse method

The orElse method returns the default value assigned with an argument if optional is empty.
otherwise, the returns value is present in the Optional class.

Optional<Integer> number1 = Optional.of(123);
System.out.println(number1.orElse(0)); // 123
Optional<Integer> number2 = Optional.empty();
System.out.println(number2.orElse(0));

Finally, you can use the orElseThrow method.

Sometimes we want to throw an error if Optional is empty, It is handy and helpful.

        Optional<Integer> number1 = Optional.of(123);
        System.out.println(number1.orElse(0)); // 123
        Optional<Integer> number2 = Optional.empty();
        System.out.println(number2.orElseThrow(Exception::new));

We can use either orElse with the default value orElseThrow method.

How to fix NoSuchElement error in java8 streams

Here is a complete example to avoid errors in the java8 stream.

It usually occurs during the streaming process with map, filter etc. methods.

We have to use orElse returns assigned default value else the return value exists in the Optional class.

import java.util.List;
import java.util.Optional;

public class Test {
    public static void main(String[] args)  throws Exception{
        List<String> srs = new ArrayList<>(Arrays.asList("one", "two", "three"));
        String result=srs.stream().filter(e->e.equals("ten")).findFirst().orElse("");
        System.out.println(result);
        String result1=srs.stream().filter(e->e.equals("one")).findFirst().orElse("");
        System.out.println(result1);

    }
}

Conclusion

You learned multiple ways to fix java.util.NoSuchElementException: No value present error in java8 streams.

The java.util.NoSuchElementException: No value present error occurred in spring boot application when an entity object is being attempted to get it from an optional object. If the hibernate returns an empty optional object, this exception Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.util.NoSuchElementException: No value present] will be thrown.The optional object should be validated before accessing the entity object in it. Otherwise, the No value present error will be thrown.

Exception

ERROR 2448 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.util.NoSuchElementException: No value present] with root cause
 java.util.NoSuchElementException: No value present
     at java.base/java.util.Optional.get(Unknown Source) ~[na:na]
     at com.yawintutor.BookController.findOne(BookController.java:42) ~[classes/:na]
     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
     at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
     at java.base/java.lang.reflect.Method.invoke(Unknown Source) ~[na:na]
     at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:798) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:94) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:na]
     at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:na]
     at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.26.jar:9.0.26]
     at java.base/java.lang.Thread.run(Unknown Source) [na:na]

How to reproduce this issue

From the rest controller, find an entity object that is not available in the database. Spring database repositories returns with optional class without any value. If you tries to access the object, it throws NoSuchElementException.

Root Cause

Access a element in an optional that has no value in it. Optional class throws no such element exception as no element available.

Solution 1

Add proper exception handling code around optional element in rest controller class

@GetMapping("/books/{id}")
Book findOne(@PathVariable Long id) {
    return repository.findById(id).get()
            .orElseThrow(() -> new Exception());
}

Solution 2

Add try catch block to catch and leave this exception

@GetMapping("/books/{id}")
Book findOne(@PathVariable Long id) {
 try {
    return repository.findById(id).get();
 } catch (Exception e) {
    // do nothing or add action code
 }
}

Solution 3

Check the url, path variables and parameters. validate with the database tables and identify why the data is not available in the database.

A quick strip down found out that.
This is the code that cause the error with LexicalPrinter

class InstallPluginCommand extends EnvironmentAwareCommand {

    /** Downloads a zip from the url, into a temp file under the given temp dir. */
    // pkg private for tests
    @SuppressForbidden(reason = "We use getInputStream to download plugins")
    Path downloadZip(Terminal terminal, String urlString, Path tmpDir, boolean isBatch) throws IOException {
        terminal.println(VERBOSE, "Retrieving zip from " + urlString);
        URL url = new URL(urlString);
        Path zip = Files.createTempFile(tmpDir, null, ".zip");
        URLConnection urlConnection = url.openConnection();
        urlConnection.addRequestProperty("User-Agent", "elasticsearch-plugin-installer");
        try (
                InputStream in = isBatch
                        ? urlConnection.getInputStream()
                        : new TerminalProgressInputStream(urlConnection.getInputStream(), urlConnection.getContentLength(), terminal)
        ) {
            // must overwrite since creating the temp file above actually created the file
            Files.copy(in, zip, StandardCopyOption.REPLACE_EXISTING);
        }
        return zip;
    }



}

Remove either one or all of 2 comment lines before @Supress make setup LexicalPrinter successfully

class InstallPluginCommand extends EnvironmentAwareCommand {


    @SuppressForbidden(reason = "We use getInputStream to download plugins")
    Path downloadZip(Terminal terminal, String urlString, Path tmpDir, boolean isBatch) throws IOException {
        terminal.println(VERBOSE, "Retrieving zip from " + urlString);
        URL url = new URL(urlString);
        Path zip = Files.createTempFile(tmpDir, null, ".zip");
        URLConnection urlConnection = url.openConnection();
        urlConnection.addRequestProperty("User-Agent", "elasticsearch-plugin-installer");
        try (
                InputStream in = isBatch
                        ? urlConnection.getInputStream()
                        : new TerminalProgressInputStream(urlConnection.getInputStream(), urlConnection.getContentLength(), terminal)
        ) {
            // must overwrite since creating the temp file above actually created the file
            Files.copy(in, zip, StandardCopyOption.REPLACE_EXISTING);
        }
        return zip;
    }



}

Issue

I have a problem with a table that has 2 types of IDs (a primary key and a foreing key). The problem originates, when I only want to retrieve those that do matchmaking with the ID of the primary key, not counting those of the foreign key passed by http.
Inside the class, I have an ID embeded as a serializable object.

When I do a search missing one of the two id’s it gives the error java.util.NoSuchElementException: No value present

My classes:

I have an order class (table) that has 2 keys. (one is a foreigner)

..
@IdClass(PedidoId.class)
public class Pedido {
    @Id
    //@GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long numero_pedido;
    @Id
    private String codigo_cliente;
..

Controller

@Autowired
private PedidoRepository eRepo;

@GetMapping("/pedidos/{id}")
public Pedido getPedidoById(@PathVariable Long id) {
    //return eRepo.findById(new PedidoId(id,"CT25")).get(); // OK
    //return eRepo.findById(new PedidoId(id,"")).get(); // ERROR
    Pedido pedido = eRepo.findById(new PedidoId(id,null)).get(); // ERROR
    // List<Pedido> pedido2 = eRepo.findByNumeroPedido(id); // CRASH  Unsatisfied dependency...
    return pedido;
}

It works correctly when I have the two Id’s with data.

The problem arises when one arrives empty. (Because we are only consulting the table itself, regardless of the foreign key)

When I use the pathUrl/pedidos/5 I get the following error

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Sep 15 14:28:15 CEST 2021
There was an unexpected error (type=Internal Server Error, status=500).
No value present
java.util.NoSuchElementException: No value present

This is due to the parameter «customer_code» (FK another table) of the OrderId object reaches null.

I think it should search the same way even if it is only for one of the 2 IDs or with all 2 at the same time. Is there any way to fix this? Or is it simply necessary to create the service -> DAO and do it manually? I think I remember that it is possible without doing it manually.

Eddited: 15/09/2021 18:07
Adding a derived query:

@Repository

public interface PedidoRepository extends JpaRepository<Pedido, PedidoId> {

     public List<Pedido> findByNumeroPedido(final Long numero_pedido);

}

If I add a derived query I get:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'pedidoController': Unsatisfied dependency expressed through field 'eRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pedidoRepository' defined in com.baeldung.core.repository.PedidoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.baeldung.core.repository.PedidoRepository.findByNumeroPedido(java.lang.Long)! Reason: Failed to create query for method public abstract java.util.List com.baeldung.core.repository.PedidoRepository.findByNumeroPedido(java.lang.Long)! No property numeroPedido found for type Pedido! Did you mean 'numero_pedido'?; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.baeldung.core.repository.PedidoRepository.findByNumeroPedido(java.lang.Long)! No property numeroPedido found for type Pedido! Did you mean 'numero_pedido'?
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:660) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1413) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.9.jar:5.3.9]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.9.jar:5.3.9]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.5.4.jar:2.5.4]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-2.5.4.jar:2.5.4]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) ~[spring-boot-2.5.4.jar:2.5.4]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) ~[spring-boot-2.5.4.jar:2.5.4]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.4.jar:2.5.4]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.4.jar:2.5.4]
    at com.baeldung.core.BaeldungReactApplication.main(BaeldungReactApplication.java:10) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.5.4.jar:2.5.4]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pedidoRepository' defined in com.baeldung.core.repository.PedidoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.baeldung.core.repository.PedidoRepository.findByNumeroPedido(java.lang.Long)! Reason: Failed to create query for method public abstract java.util.List com.baeldung.core.repository.PedidoRepository.findByNumeroPedido(java.lang.Long)! No property numeroPedido found for type Pedido! Did you mean 'numero_pedido'?; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.baeldung.core.repository.PedidoRepository.findByNumeroPedido(java.lang.Long)! No property numeroPedido found for type Pedido! Did you mean 'numero_pedido'?
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657) ~[spring-beans-5.3.9.jar:5.3.9]
    ... 25 common frames omitted
Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.baeldung.core.repository.PedidoRepository.findByNumeroPedido(java.lang.Long)! Reason: Failed to create query for method public abstract java.util.List com.baeldung.core.repository.PedidoRepository.findByNumeroPedido(java.lang.Long)! No property numeroPedido found for type Pedido! Did you mean 'numero_pedido'?; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.baeldung.core.repository.PedidoRepository.findByNumeroPedido(java.lang.Long)! No property numeroPedido found for type Pedido! Did you mean 'numero_pedido'?
    at org.springframework.data.repository.query.QueryCreationException.create(QueryCreationException.java:101) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:106) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(QueryExecutorMethodInterceptor.java:94) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133) ~[na:na]
    at java.base/java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Collections.java:1056) ~[na:na]
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.mapMethodsToQuery(QueryExecutorMethodInterceptor.java:96) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$new$0(QueryExecutorMethodInterceptor.java:86) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at java.base/java.util.Optional.map(Optional.java:260) ~[na:na]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.<init>(QueryExecutorMethodInterceptor.java:86) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:360) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:323) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:230) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.util.Lazy.get(Lazy.java:114) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:329) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:144) ~[spring-data-jpa-2.5.4.jar:2.5.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1845) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782) ~[spring-beans-5.3.9.jar:5.3.9]
    ... 35 common frames omitted
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.baeldung.core.repository.PedidoRepository.findByNumeroPedido(java.lang.Long)! No property numeroPedido found for type Pedido! Did you mean 'numero_pedido'?
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:96) ~[spring-data-jpa-2.5.4.jar:2.5.4]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:107) ~[spring-data-jpa-2.5.4.jar:2.5.4]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:218) ~[spring-data-jpa-2.5.4.jar:2.5.4]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:81) ~[spring-data-jpa-2.5.4.jar:2.5.4]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:102) ~[spring-data-commons-2.5.4.jar:2.5.4]
    ... 57 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property numeroPedido found for type Pedido! Did you mean 'numero_pedido'?
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:90) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:437) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:413) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.mapping.PropertyPath.lambda$from$0(PropertyPath.java:366) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at java.base/java.util.concurrent.ConcurrentMap.computeIfAbsent(ConcurrentMap.java:330) ~[na:na]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:348) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:331) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:81) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.lambda$new$0(PartTree.java:249) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na]
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:250) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.lambda$new$0(PartTree.java:383) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na]
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:384) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:95) ~[spring-data-commons-2.5.4.jar:2.5.4]
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:89) ~[spring-data-jpa-2.5.4.jar:2.5.4]
    ... 61 common frames omitted

Solution:

Rename the variable numero_pedidode to numeroPedido from the Pedidos class and it worked.

  1. Add the method «public List findByNumeroPedido(final Long numero_pedido);» inside the repository

  2. Rename the variable numero_pedidode to numeroPedido from the Pedidos class

Solution

Since the Pedido class has a composite primary key, querying the respective repository with numero_pedido would result in a collection of results. I would adapt the Repository to look something like so:

@Repository
public interface PedidoRepository extends JpaRepository<Pedido, PedidoId>{

    (...)

    public List<Pedido> findByNumeroPedido(final Long numero_pedido);

}

You could use this method to get a list of Pedido’s and process them afterwards as required.

If you are interested in any Pedido with a specific numero_pedido, you could also implement one of the following repository methods:

        public Pedido findFirstByNumeroPedido(final Long numero_pedido);
        public Pedido findAnyByNumeroPedido(final Long numero_pedido);

Here is a small tutorial from Baeldung on this.

Answered By – Vasco

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Понравилась статья? Поделить с друзьями:
  • No such ship design stellaris ошибка
  • No such node general самп ошибка
  • No such instance ошибка snmp 223
  • No such file or directory python ошибка
  • No such file or directory git bash ошибка