Creating Resource with references using spring data rest

泪湿孤枕 提交于 2019-11-29 17:45:59

It can be achieved by using a custom HttpMessageConverter and defining a custom content-type which can be anything other than standard (I used application/mjson):

MHttpMessageConverter.java

public class MHttpMessageConverter implements HttpMessageConverter<Object>{
    @Override
    public boolean canRead(Class<?> aClass, MediaType mediaType) {
        if (mediaType.getType().equalsIgnoreCase("application")
                && mediaType.getSubtype().equalsIgnoreCase("mjson"))
            return true;
        else
            return false;
    }

    @Override
    public boolean canWrite(Class<?> aClass, MediaType mediaType) {
        return false;
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return new ArrayList<>(Arrays.asList(MediaType.APPLICATION_JSON));
    }

    @Override
    public Object read(Class<?> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        ObjectMapper mapper = new ObjectMapper();
        Object obj = mapper.readValue(httpInputMessage.getBody(),aClass);
        return obj;
    }

    @Override
    public void write(Object o, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {

    }
}

CustomRestConfiguration.java

@Configuration
public class CustomRestConfiguration extends RepositoryRestConfigurerAdapter {

    @Override
    public void configureHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
        messageConverters.add(new MHttpMessageConverter());
    }
}

Spring Data REST is using HATEOAS. To refer to associated resources we have to use links to them:

Create a hospital first

POST /api/hospitals
{
    //...
}

response

{
    //...
    "_links": [
        "hostpital": "http://localhost/api/hospitals/1",
        //...
    ]
}

Then get 'hospital' (or 'self') link and add it to the 'donationRequests' payload

POST /api/donationRequests
{
    "bloodGroup":"AB+",
    "hospital": "http://localhost/api/hospitals/1"
}

Another approach - create first 'donationRequests' without hospital

POST /api/donationRequests
{
    //...
}

response

{
    //...
    "_links": [
        "hostpital": "http://localhost/api/donationRequests/1/hospital"
        //...
    ]
}

then PUT hospital to donationRequests/1/hospital using text link to hospital in your payload (pay attention to Content-Type: text/uri-list)

PUT http://localhost/api/donationRequests/1/hospital (Content-Type: text/uri-list)
http://localhost/api/hospitals/1

Info: Repository resources - The association resource

UPDATE

If it's necessary to deal without links to resources we have to make a custom rest controller.

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