如何在 Spring Boot 应用程序中将 java lang long 转换为实体类

Posted

技术标签:

【中文标题】如何在 Spring Boot 应用程序中将 java lang long 转换为实体类【英文标题】:How to cast java lang long to entity class in SpringBoot application 【发布时间】:2021-12-14 07:00:55 【问题描述】:

我创建了一个应用程序,当我去更新我的数据库中的一列时,我 得到这种类型的错误。

java.lang.ClassCastException: class com.nilmani.jobworkmanagement.entity.DepositMaterial cannot be cast to class java.lang.Long (com.nilmani.jobworkmanagement.entity.DepositMaterial is in unnamed module of loader 'app'; java.lang.Long is in module java.base of loader 'bootstrap')
    at com.sun.proxy.$Proxy93.findByUserId(Unknown Source) ~[na:na]
    at com.nilmani.jobworkmanagement.service.DepositService.updateDeposit(DepositService.kt:43) ~[main/:na]
    at com.nilmani.jobworkmanagement.controller.AdminMaterialController.updateMaterial(AdminMaterialController.kt:49) ~[main/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[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:564) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-5.3.12.jar:5.3.12]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:880) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.54.jar:4.0.FR]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.12.jar:5.3.12]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.12.jar:5.3.12]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:90) ~[spring-web-5.3.12.jar:5.3.12]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.12.jar:5.3.12]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.12.jar:5.3.12]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.12.jar:5.3.12]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]

DepositMaterial.kt

package com.nilmani.jobworkmanagement.entity

import javax.persistence.*

@Entity
data class DepositMaterial(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "depositId")
    val id: Long = -1,
    val userId: Long = -1,
    val totalPieces: Long = -1,
    val deposit: Long = -1,
    val pending: Long = totalPieces-deposit,
    val workStatus: Boolean = false

)

ReqUpdateDeposit.kt

package com.nilmani.jobworkmanagement.model.request

data class ReqUpdateDeposit(
    val userId:Long=-1,
    val pending:Long=-1,
)

DepositService.kt

package com.nilmani.jobworkmanagement.service

import com.nilmani.jobworkmanagement.entity.DepositMaterial
import com.nilmani.jobworkmanagement.model.request.ReqDeposit
import com.nilmani.jobworkmanagement.model.request.ReqUpdateDeposit
import com.nilmani.jobworkmanagement.repository.DepositRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import kotlin.jvm.Throws

@Service
class DepositService 
    @Autowired
    private lateinit var depositRepository: DepositRepository
    
    @Throws(Exception::class)
    fun updateDeposit(request : ReqUpdateDeposit):DepositMaterial
        val existingUser = depositRepository.findByUserId(request.userId)
        if (existingUser == request.userId)
            if (request.pending.equals(0))
                depositRepository.updateWorkStatus(true,request.userId)
            else
                println("you have still pending materials")
            
        
        else
            println("Enter a valid userId")
        
        return DepositMaterial()
    


DepositMaterialRepository.kt

package com.nilmani.jobworkmanagement.repository

import com.nilmani.jobworkmanagement.entity.DepositMaterial
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.web.bind.annotation.RequestParam
import javax.transaction.Transactional

interface DepositRepository : JpaRepository<DepositMaterial, Long> 
    /** find user by userID*/
    fun findByUserId(userId: Long):Long

    @Transactional
    @Modifying
    @Query("update DepositMaterial d set d.workStatus =:workStatus where d.userId =:userId")
    fun updateWorkStatus(@RequestParam("workStatus")workStatus: Boolean,userId: Long)

AdminMaterialController.kt

package com.nilmani.jobworkmanagement.controller

import com.nilmani.jobworkmanagement.model.request.ReqDeposit
import com.nilmani.jobworkmanagement.model.request.ReqUpdateDeposit
import com.nilmani.jobworkmanagement.model.request.ReqWithdrawMaterial
import com.nilmani.jobworkmanagement.model.response.ResMessage
import com.nilmani.jobworkmanagement.model.response.RespDeposit
import com.nilmani.jobworkmanagement.model.response.RespWithdrawMaterial
import com.nilmani.jobworkmanagement.service.DepositService
import com.nilmani.jobworkmanagement.service.WithdrawMaterialService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/admin")
class AdminMaterialController 
    @Autowired
    private lateinit var materialService: WithdrawMaterialService
    @Autowired
    private lateinit var depositService: DepositService
    
    @PatchMapping("/verifyWorkstatus")
    fun updateMaterial(@ModelAttribute request: ReqUpdateDeposit):ResponseEntity<*>
        val updateWork = depositService.updateDeposit(request)
        return ResponseEntity(ResMessage("Update success full"),HttpStatus.OK)
    

这个问题的原因是什么,没有我在哪里转换长变量 与实体类,我只是调用实体类变量 访问和更新 DepositMaterial 工作状态列

【问题讨论】:

尝试将@RequestParam 注释添加到存储库中的userId 参数中。 【参考方案1】:

这部分代码

val existingUser = depositRepository.findByUserId(request.userId)
if (existingUser == request.userId)

您正在将 DepositMaterial(existingUser) 对象与长对象 (request.userId) 进行比较。这是错误的。还有为什么在您已经从存储库中获得实体时需要比较它。此外,由于您将 id 定义为 Long(不是原始类型),因此您需要使用 equals。反正你可以这样比较

if (existingUser.id.equals(request.userId))

【讨论】:

这些数字应该与equals()进行比较 if (existingUser.id.equals(request.userId)) 你是对的,因为它没有被定义为原始它应该是相等的。更新了我的答案

以上是关于如何在 Spring Boot 应用程序中将 java lang long 转换为实体类的主要内容,如果未能解决你的问题,请参考以下文章

如何在弹性beantalk中将PostgreSQL RDS连接到spring boot?

如何在 Spring Boot 应用程序中将 java lang long 转换为实体类

如何在 docker run 命令中将 Java 选项/变量传递给 Spring Boot 应用程序

如何在 Spring Boot 中将 HikariCP 与两个数据源结合使用 Flyway

如何在 Spring Boot 中将 Cache-Control 标头添加到静态资源?

如何在 Spring Boot 中将 mongo db update 运算符应用为 $inc