Spring Data REST - POST new entity with relationships

自古美人都是妖i 提交于 2019-11-30 13:50:48

问题


Relates to: Spring Data Rest version 2.0.2

I'm trying to POST an entity (Address) with a @ManyToOne (instead of @OneToOne as in example) relationship to Person as explained in: Embedded Entity references in complex object graphs but I get a Jackson Error:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: (was java.lang.NullPointerException) (through reference chain: Address["person"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: Address["person"])
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:228) ~[spring-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]

I find it strange that I can send a JSON object with rel and href in the "person" attribute of Address like:

"person": {
    "rel" : "people.Person",
    "href" : "http://localhost:8080/people/1"
}

Is this still valid? The refered page is quite old (2012). Are there any updated docs. I have reviewed the reference doc even for latest (to date) 2.1.0 RC1, but I find it lacking.

Any pointer would be appreciated.

Stackoverflow suggested me to see this question, which, in my case fail with a HTTP Status 405 - Request method 'POST' not supported ... which is probably a configuration issue, but my original question stands.

Update 1: From the Reference Doc section 4.1 it says:

Sometimes the behavior of the Spring Data REST's ObjectMapper, which has been specially configured to use intelligent serializers that can turn domain objects into links and back again, may not handle your domain model correctly. There are so many ways one can structure your data that you may find your own domain model isn't being translated to JSON correctly. It's also sometimes not practical in these cases to try and support a complex domain model in a generic way. Sometimes, depending on the complexity, it's not even possible to offer a generic solution.

The problem could be that I'm using a custom Jackson ObjectMapper with Hibernate support. I'll try to dig further.

Update 2: Never mind update 1, I removed the Hibernate4Module and the behaviour is the same.


回答1:


The format on the page you linked to was out of date. I just updated it. The correct format is:

{
    "postalCode": "12345",
    "province": "MO",
    "lines": ["1 W 1st St."],
    "city": "Univille",
    "person": "http://localhost:8080/people/1"
}

At least, this is what works for me with my entities.



来源:https://stackoverflow.com/questions/23767233/spring-data-rest-post-new-entity-with-relationships

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