【发布时间】:2017-12-28 09:29:27
【问题描述】:
我有一个模型:
public class MyModel {
@Id private Long id;
private Long externalId;
// Getters, setters
}
我想使用externalId 作为我的资源标识符:
@Configuration
static class RepositoryEntityLookupConfig extends RepositoryRestConfigurerAdapter {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration configuration) {
configuration
.withEntityLookup()
.forRepository(MyRepository.class, MyModel::getExternalId, MyRepository::findByExternalId);
}
}
如果externalId 是String,这可以正常工作。但既然是数字 (Long)
public interface MyRepository extends JpaRepository<MyModel, Long> {
Optional<MyModel> findByExternalId(@Param("externalId") Long externalId);
}
调用时:/myModels/1 我得到:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long
at org.springframework.data.rest.core.config.EntityLookupConfiguration$RepositoriesEntityLookup.lookupEntity(EntityLookupConfiguration.java:213) ~[spring-data-rest-core-2.6.4.RELEASE.jar:na]
at org.springframework.data.rest.core.support.UnwrappingRepositoryInvokerFactory$UnwrappingRepositoryInvoker.invokeFindOne(UnwrappingRepositoryInvokerFactory.java:130) ~[spring-data-rest-core-2.6.4.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.RepositoryEntityController.getItemResource(RepositoryEntityController.java:524) ~[spring-data-rest-webmvc-2.6.4.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.RepositoryEntityController.getItemResource(RepositoryEntityController.java:335) ~[spring-data-rest-webmvc-2.6.4.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_111]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_111]
...
一个单独的自定义 EntityLookupSupport<MyModel> 组件类有效。
我是否遗漏了一些东西来让它为Long 使用我的RepositoryRestConfigurerAdapter 中的方法引用?
【问题讨论】:
-
底层数据库列的类型是什么?该列是字符串吗?
-
@Ben 数据库列类型:int,数据库:MySQL。如果类型是 String,它可以工作(不需要转换器,模型字段将是 String 而不是 Long)。我需要它来处理 int 类型(外键约束)。
-
如果您调用
/myModels/1L而不是/myModels/1怎么办?可能是序列化问题
标签: spring spring-data-jpa spring-data-rest