How to expose @EmbeddedId converters in Spring Data REST

随声附和 提交于 2019-11-27 02:00:06

问题


There are some Entities with composite Primary Keys and these entities when exposed are having incorrect Links having full qualified name of classes in URL inside _links

Also clicking on links gives such errors -

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

I have XML configured Spring Repository with jpa:repositories enabled and Respository extending from JpaRepository

Can I make Repository implement org.springframework.core.convert.converter.Converter to handle this. Currently getting links as below -

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

in xml config , I have jpa:repositories enabled and @RestResource enabled inside Repositories


回答1:


At first you need to get a usable link. Currently your composite id is exposed as com.core.connection.domains.UserFriendshipId@5b10. It should be enough to override the toString method of UserFriendshipIdto produce something useful like 2-3.

Next you need to implement a converter so that 2-3 can be converted back to a UserFriendshipId:

class UserFriendShipIdConverter implements Converter<String, UserFriendshipId> {

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

Finally you need to register the converter. You already suggested to override configureConversionService:

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

If you prefer a XML configuration you can follow the instructions in the documentation.




回答2:


To expand on the accepted answer.. when using spring-boot, in order to get this to work, my class that extends RepositoryRestMvcConfiguration also needed to have the @Configuration annotation. I also needed to add the following annotation to my spring boot application class:

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

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

I also called the super method within my method that overrides configureConversionService:

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

This preserves the default converters, and then adds yours



来源:https://stackoverflow.com/questions/26249506/how-to-expose-embeddedid-converters-in-spring-data-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!