Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expose @EmbeddedId converters in Spring Data REST

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

like image 713
fortm Avatar asked Oct 08 '14 05:10

fortm


2 Answers

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.

like image 124
a better oliver Avatar answered Oct 20 '22 04:10

a better oliver


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

like image 26
habelson Avatar answered Oct 20 '22 05:10

habelson