Spring 数据 JPA findById() 抛出 ClassCastException

Spring Data JPA findById() throwing ClassCastException

我有一个使用 Spring Data JPA 的 findById() 方法的方法。但是,此方法在我调用 findById():

的 getSupportedKey() 方法的第 1 行返回 ClassCastException
MySupportedKey cannot be cast to java.util.Optional

private MySupportedKey getSupportedKey(String tenant, String key) {
        Optional<MySupportedKey> mySupportedKeyOptional = mySupportedKeyRepository.findById(new MySupportedKeyId(tenant, key));
        MySupportedKey mySupportedKey= null;
        if(mySupportedKeyOptional !=null) {
             mySupportedKey= mySupportedKeyOptional.orElse(null);
        }
        return mySupportedKey;
    }

我一直在敲我的头很长时间,但我什么也没得到。请帮我解决这个问题。我正在使用 spring-data-jpa: 2.0.8.RELEASE.

添加存储库源代码:

public interface MySupportedKeyRepository extends JpaRepository<MySupportedKey, MySupportedKeyId> {

List<MySupportedKey> findByIdTenant(@NotNull String tenant);
}

添加错误的完整堆栈跟踪:

java.lang.ClassCastException: com.test.service.user.entity.MySupportedKey cannot be cast to java.util.Optional
at com.test.service.user.repository.MySupportedKeyRepository$MockitoMock04362870.findById(Unknown Source)
at com.test.service.user.repository.MySupportedKeyRepository$MockitoMock04362870.findById(Unknown Source)
at com.test.service.user.userpreferences.PreferencesServiceImpl.getSupportedKey(PreferencesServiceImpl.java:217)
at com.test.service.user.userpreferences.PreferencesServiceImpl.updateUserPreferences(PreferencesServiceImpl.java:167)
at com.test.service.user.userpreferences.PreferencesServiceImpl.lambda(PreferencesServiceImpl.java:92)
at java.util.ArrayList.forEach(Unknown Source)
at com.test.service.user.userpreferences.PreferencesServiceImpl.updateUserPreferences(PreferencesServiceImpl.java:92)
at com.test.service.user.preferences.PreferencesServiceImplTest.updateUserPreferences(PreferencesServiceImplTest.java:300)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.mockito.internal.junit.JUnitRule.evaluateSafely(JUnitRule.java:52)
at org.mockito.internal.junit.JUnitRule.evaluate(JUnitRule.java:43)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.RunPrepareTestInstanceCallbacks.evaluate(RunPrepareTestInstanceCallbacks.java:64)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.springframework.test.context.junit4.statements.SpringFailOnTimeout.evaluate(SpringFailOnTimeout.java:87)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access[=13=]0(ParentRunner.java:58)
at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
at org.springframework.test.context.junit4.rules.SpringClassRule$TestContextManagerCacheEvictor.evaluate(SpringClassRule.java:230)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

您为存储库设置了一个 Mockito 模拟,并可能告诉它在 findById 被调用时 return 一个 MySupportedKey 实例。 但是由于 findById 应该 return 一个 Optional 你现在得到了例外。

您可以在堆栈跟踪的前两行中看到这是来自 Mockito。

java.lang.ClassCastException: com.test.service.user.entity.MySupportedKey cannot be cast to java.util.Optional
at com.test.service.user.repository.MySupportedKeyRepository$MockitoMock04362870.findById(Unknown Source)

修改以下方法中的 Optional 处理以获得如下所示的正确表示:

private MySupportedKey getSupportedKey(String tenant, String key) {
            Optional<MySupportedKey> mySupportedKeyOptional = mySupportedKeyRepository.findById(new MySupportedKeyId(tenant, key));
            MySupportedKey mySupportedKey= null;
            if(mySupportedKeyOptional.isPresent()) {
                 mySupportedKey= mySupportedKeyOptional.get();
            }
            return mySupportedKey;
        }

无法添加评论,只是想详细说明 Jens 的回答,因为我花了一段时间才弄清楚如何解决这个问题(作为新手)。 为了解决这个问题,我更改了我的代码:

when(mongoRepository.findById(Mockito.anyString())).thenAnswer(new Answer<MongoObj>() {
        @Override
        public MongoObj answer(InvocationOnMock invocation) throws Throwable {
            MongoObj repush = new MongoObj();
            //Some other code

            return repush;
        }
    });

when(mongoRepository.findById(Mockito.anyString())).thenAnswer(new Answer<Optional<MongoObj>>() {
        @Override
        public Optional<MongoObj> answer(InvocationOnMock invocation) throws Throwable {
            MongoObj repush = new MongoObj();
            //Some other code

            return Optional.of(repush);
        }
    });

希望对您有所帮助!