2

Before AJAX was popular, it was possible to convert between id's and entities by using a custom property editor and registering that in your controllers. So if you had a User form backing object that contained a Company, if company.id was 5, Spring would call your custom property editor to so that you could go fetch the Company with id 5 and set it onto your user.company property.

Now in the Ajax way of doing things, we have similar requirements. Instead of using a form backing object, we want to do an HTTP POST or PUT of a User object as JSON data and have Spring automatically convert that JSON to a User object on our behalf. Spring has made this possible with the @RequestBody annotation, and by using Jackson to marshall the JSON back and forth to Java objects.

This is just a fictitious example. Imagine a User containing a Company object with the appropriate getters/setters.

@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void create(@Valid @RequestBody User user) {
    userService.saveUser(user);
}

Since property editors are a thing of the past as far as Spring is concerned, we are expected to use the new Conversion Service API. For my application, I have successfully created a factory that does what my old property editor did before - converting id's back to entities.

My question is, how can I get Spring to call into the conversion service during or after Jackson marshals the JSON data? I know it is possible to create a custom JsonDeserializer, but I find writing/testing these to be a pain and lengthy process as I need to do it for a massive number of entities, and each deserializer would take anywhere from 60 to 200 lines of code each.

I'd love it if Spring could do the id to entity mapping for me on my behalf, just as it did for form backing objects. Is there a way?

4

2 回答 2

0

The M. Deinum's answer was great. But for a practical work , think about AOP ;) It can be interesting to use it in your problem :).

于 2013-10-01T09:42:44.620 回答
0

在这种情况下,它仅适用于根对象User,不适用于嵌套组件。Spring Data REST 有一个“DomainClassConverter”,您可以查看它。

基本上你想创建ConditionalGenericConverter检查它是否可以转换请求的对象(即它可以由EntityManager/加载SessionFactory)。(这里是无条件版本。

这一切都对 REST(基本上)在服务器端进行查找有点不利,因为您应该发送请求所需的所有内容(表示状态传输和超媒体作为所有状态的传输引擎)。但这是另一个讨论:)。

链接

  1. 域实体转换器博客
  2. 弹簧参考指南
于 2013-09-30T07:57:18.597 回答