gpt4 book ai didi

java - spring data jpa - 基于接口(interface)的投影中的自定义类型转换

转载 作者:行者123 更新时间:2023-11-30 09:59:58 27 4
gpt4 key购买 nike

我正在尝试实现 Interface-based Projection但我无法让它与我的自定义类型列一起使用。

下面是我正在尝试做的事情的例子:

存储库:

@Query(value = "SELECT customType from TABLE", nativeQuery = true)
List<TestClass> getResults();

界面投影:

public interface TestClass {
@Convert(converter = MyCustomTypeConverter.class)
MyCustomType getCustomType();
}

转换器:

@Converter
public class MyCustomTypeConverter implements Converter<String, MyCustomType> {

@Override
public MyCustomType convert(String source) {
// whatever
}
}

当我在存储库上调用 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)

我发现问题出在

org.springframework.data.projection.ProxyProjectionFactory

使用

org.springframework.core.convert.support.DefaultConversionService

这显然没有注册我的自定义类型转换器。

如果我在 ConversionService 中的断点处停止并在运行时手动添加我的转换器,投影将毫无问题地工作。

所以问题是:在基于接口(interface)的投影期间,我能否以某种方式将我的自定义转换器注册到 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());
}
}

最佳答案

使用的 ConversionServiceDefaultConversionService.getSharedInstance()

因此您应该能够访问它并添加您的转换器。

关于java - spring data jpa - 基于接口(interface)的投影中的自定义类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58417190/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com