I am using spring data rest, I have following entities exposed via spring data rest
DonationRequest
@Data
@Entity
@Table(name=\"donation_request\",sc
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.