ki7*_*yl3 6 java projection converters nativequery spring-data-jpa
我正在尝试实现基于接口的投影,但无法使其与我的自定义类型列一起使用。
下面是我正在尝试做的示例:
存储库:
@Query(value = "SELECT customType from TABLE", nativeQuery = true)
List<TestClass> getResults();
Run Code Online (Sandbox Code Playgroud)
界面投影:
public interface TestClass {
@Convert(converter = MyCustomTypeConverter.class)
MyCustomType getCustomType();
}
Run Code Online (Sandbox Code Playgroud)
转换器:
@Converter
public class MyCustomTypeConverter implements Converter<String, MyCustomType> {
@Override
public MyCustomType convert(String source) {
// whatever
}
}
Run Code Online (Sandbox Code Playgroud)
当我在存储库上调用 getResults() 时,我会按预期收到结果列表,但是当我尝试对其中一个结果调用 getCustomType() 时,出现异常:
java.lang.IllegalArgumentException: Projection type must be an interface!
at org.springframework.util.Assert.isTrue(Assert.java:118)
at org.springframework.data.projection.ProxyProjectionFactory.createProjection(ProxyProjectionFactory.java:100)
at org.springframework.data.projection.SpelAwareProxyProjectionFactory.createProjection(SpelAwareProxyProjectionFactory.java:45)
at org.springframework.data.projection.ProjectingMethodInterceptor.getProjection(ProjectingMethodInterceptor.java:131)
at org.springframework.data.projection.ProjectingMethodInterceptor.invoke(ProjectingMethodInterceptor.java:80)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.ProxyProjectionFactory$TargetAwareMethodInterceptor.invoke(ProxyProjectionFactory.java:245)
Run Code Online (Sandbox Code Playgroud)
我发现问题出在
org.springframework.data.projection.ProxyProjectionFactory
Run Code Online (Sandbox Code Playgroud)
它使用
org.springframework.core.convert.support.DefaultConversionService
Run Code Online (Sandbox Code Playgroud)
这显然没有注册我的自定义类型转换器。
如果我在 ConversionService 中的断点处停止并在运行时手动添加我的转换器,投影将正常工作。
所以问题是:我可以在基于接口的投影期间以某种方式将我的自定义转换器注册到 spring jpa 使用的 ConversionService 吗?
编辑:
我在 InitializingBean 中将我的转换器添加到 DefaultConversionService 的 sharedInstance 中,如下所示,它工作正常。
@Component
public class DefaultConversionServiceInitializer implements InitializingBean {
@Override
public void afterPropertiesSet() {
DefaultConversionService conversionService = (DefaultConversionService) DefaultConversionService.getSharedInstance();
conversionService.addConverter(new MyCustomTypeConverter());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2324 次 |
| 最近记录: |