Java 存在可选的长参数但不能转换为空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23977629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:30:03  来源:igfitidea点击:

Optional long parameter is present but cannot be translated into a null value

javajakarta-eeexceptioncontrollerdao

提问by Erez

Hi i'm developing on web so i have an ajax function which calling to a controller function which calling to a DAO function (to make changes on DB). I'm getting the exception above in the controller function..

嗨,我正在 Web 上开发,所以我有一个 ajax 函数,它调用一个控制器函数,该函数调用一个 DAO 函数(在 DB 上进行更改)。我在控制器功能中遇到上述异常..

controller function:

控制器功能:

@RequestMapping(value="/changeIsPublic", method=RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public  @ResponseBody boolean changeIsPublic(HttpServletRequest request, Locale locale, Model model, long transactionId, boolean isPublic) {
    boolean result = false; 
    try {
            boxDao.changeIsPublicStatus(transactionId, isPublic);
            result = true;

        } catch (Exception e) {
            logger.debug("Failed to publish transaction. transaction ID: " + transactionId + e.getMessage());
        }
        return result;
}

DAO function:

DAO函数:

public Box changeIsPublicStatus(long id, boolean isPublic) {
    Criteria criteria = getCurrentSession().createCriteria(Box.class);
    criteria.add(Restrictions.eq("id", id));
    Box transaction = (Box) criteria.uniqueResult();
    transaction.setIsPublic(isPublic);
    return transaction;
}

exception:

例外:

    SEVERE: Servlet.service() for servlet [appServlet] in context with path [/goblin] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Optional long parameter 'transactionId' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.] with root cause
java.lang.IllegalStateException: Optional long parameter 'transactionId' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.
    at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.handleNullValue(AbstractNamedValueMethodArgumentResolver.java:188)
    at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:94)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:123)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:149)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.yes.java.security.AuthenticationFilter.doFilter(AuthenticationFilter.java:105)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)    `

采纳答案by alfasin

The error is pretty much self explanatory: you can't declare a primitive to be null,
for example: private int myNumber = null;will not compile. So instead of using longuse Longand you should be good to go.

该错误几乎不言自明:您不能将原语声明为null
例如:private int myNumber = null;不会编译。所以不要使用longuse Long,你应该很高兴去。

回答by gefrag

Exception message guides you. Change long type to Long

异常消息为您提供指导。将 long 类型更改为 Long

回答by Ahmed Tawila

I got this error when I was working with Hymanson REST web services (RESTful Spring Controllers). The problem was that I forgot the @PathVariableannotation which tells the web service where it should receive your input to produce the response so it did not know where I should be passing my input. My fix was:

我在使用 Hymanson REST Web 服务(RESTful Spring 控制器)时遇到此错误。问题是我忘记了@PathVariable注释,它告诉 Web 服务它应该在哪里接收您的输入以生成响应,因此它不知道我应该在哪里传递我的输入。我的解决方法是:

@RequestMapping(value = "/supplier/{supplierId}")
public List<PurchaseInvoice> getPurchaseInvoicesBySupplierId(@PathVariable int supplierId) {
    return purchaseInvoiceService.getPurchaseInvoicesBySupplierId(supplierId);
}

回答by Frank.Chang

Some basic concept for beginner from What is the difference between long and Long in android code?

初学者的一些基本概念来自Android代码中的long和Long有什么区别?

Long is a class. long is a primitive. That means Long can be null, where long can't. Long can go anywhere that takes an Object, long can't (since it isn't a class it doesn't derive from Object).

Java will usually translate a Long into a long automatically (and vice versa), but won't for nulls (since a long can't be a null), and you need to use the Long version when you need to pass a class (such as in a generic declaration).

长是一个类。long 是一个原始类型。这意味着 Long 可以为 null,而 long 不能为 null。Long 可以去任何需要 Object 的地方, long 不能(因为它不是一个类,它不是从 Object 派生的)。

Java 通常会自动将 Long 转换为 long(反之亦然),但不会为空值(因为 long 不能为空值),并且在需要传递类时需要使用 Long 版本(例如在通用声明中)。

回答by Prabhakar

@Ahmed Tawila - as he mentioned I did the same mistake. I forgot to add @PathVariableannotation before the primitive type for the method in controller.

@Ahmed Tawila - 正如他所说,我犯了同样的错误。我忘@PathVariable了在控制器中方法的原始类型之前添加注释。

Incorrect Code: Required annotation is not defined before long primitive type

不正确的代码:在 long 原始类型之前未定义所需的注释

@RequestMapping(method = RequestMethod.DELETE, value = "/categories/{categoryId}/subcategories/{id}")
public void deleteSubCategory(long id) throws Exception {
    subCategoryService.delete(id);
}

Correct Code: Annotation added(@PathVariable)

正确代码:添加注释( @PathVariable)

@RequestMapping(method = RequestMethod.DELETE, value = "/categories/{categoryId}/subcategories/{id}")
public void deleteSubCategory(@PathVariable long id) throws Exception {
    subCategoryService.delete(id);
}

回答by R acharya

This is sometime caused by using PathParam instead of PathVariable. this could be just another solution. We can take a look at it as well. I faced similar situation while implementing Spring data jpa with JpaRepository interface.

这有时是由使用 PathParam 而不是 PathVariable 引起的。这可能只是另一种解决方案。我们也可以看看。我在使用 JpaRepository 接口实现 Spring data jpa 时遇到了类似的情况。

回答by Kanagalingam

In my case, I was missing @RequestBodyAnnotation in the request body in Controller!

就我而言,我@RequestBodyController的请求正文中缺少Annotation !

public View updateView(@RequestBody int id){
}

Hope it helps someone!

希望它可以帮助某人!

回答by softwarevamp

Annotate with: @RequestParam(defaultValue = "0").

注释: @RequestParam(defaultValue = "0")