SpringBoot更新数据库时DepositMaterial转Long的ClassCastException问题排查
错误根本原因
你在DepositRepository中定义的findByUserId方法返回类型配置错误:
Spring Data JPA根据方法名findByUserId会默认返回匹配到的DepositMaterial实体类对象,但你将该方法的返回值声明为Long类型,框架在执行完查询后会自动尝试将实体对象强制转换为Long,就触发了你看到的类转换异常。
修复步骤
- 修正
DepositRepository中findByUserId方法的返回类型
如果业务中userId唯一,对应单条DepositMaterial记录,修改为:
/** find user by userID*/ fun findByUserId(userId: Long): DepositMaterial?
如果一个userId可对应多条记录,修改为:
/** find user by userID*/ fun findByUserId(userId: Long): List<DepositMaterial>
- 修正
DepositService中updateDeposit方法的判断逻辑
原来的逻辑是直接拿返回结果和request.userId比对,修改为取实体的userId属性比对,以单条记录场景为例:
@Throws(Exception::class) fun updateDeposit(request : ReqUpdateDeposit):DepositMaterial{ val existingDeposit = depositRepository.findByUserId(request.userId) if (existingDeposit != null){ if (request.pending == 0L){ depositRepository.updateWorkStatus(true,request.userId) }else{ println("you have still pending materials") } return existingDeposit }else{ println("Enter a valid userId") return DepositMaterial() } }
内容的提问来源于stack exchange,提问作者Mama
相关产品推荐
相关产品推荐

