繁体   English   中英

如何在Spring Data REST中公开@EmbeddedId转换器

[英]How to expose @EmbeddedId converters in Spring Data REST

有些实体具有复合主键,并且这些实体在公开时具有错误的链接,在_links中的URL中具有类的完全限定名称

点击链接也会出现这样的错误 -

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type java.lang.String to type com.core.connection.domains.UserFriendshipId

我有XML配置的Spring Repository和jpa:启用了存储库,还有从JpaRepository扩展的Respository

我可以使用Repository实现org.springframework.core.convert.converter.Converter来处理这个问题。 目前获得如下链接 -

_links: {
userByFriendshipId: {
href: "http://localhost:8080/api/userFriendships/com.core.connection.domains.UserFriendshipId@5b10/userByFriendId"
}

在xml配置中,我在存储库中启用了jpa:repositories和@RestResource

首先,您需要获得可用的链接。 目前,您的复合ID公开为com.core.connection.domains.UserFriendshipId@5b10 应该足以覆盖UserFriendshipIdtoString方法UserFriendshipId成像2-3这样有用的东西。

接下来,您需要实现转换器,以便2-3可以转换回UserFriendshipId

class UserFriendShipIdConverter implements Converter<String, UserFriendshipId> {

  UserFriendShipId convert(String id) {
    ...
  }
}

最后,您需要注册转换器。 您已建议覆盖configureConversionService

protected void configureConversionService(ConfigurableConversionService conversionService) {
   conversionService.addConverter(new UserFriendShipIdConverter());
} 

如果您更喜欢XML配置,则可以按照文档中的说明进行操作

为了扩展已接受的答案..当使用spring-boot时,为了使其工作,扩展RepositoryRestMvcConfiguration类也需要具有@Configuration注释。 我还需要在弹簧启动应用程序类中添加以下注释:

@SpringBootApplication
@Import(MyConfiguration.class)
public class ApplicationContext {

    public static void main(String[] args) {
        SpringApplication.run(ApplicationContext.class,args);
    }
}

我还在我的方法中调用了覆盖configureConversionService的super方法:

    @Override
    protected void configureConversionService(ConfigurableConversionService conversionService) {
        super.configureConversionService(conversionService);
        conversionService.addConverter(new TaskPlatformIdConverter());
    }

这将保留默认转换器,然后添加您的转换器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM