简体   繁体   中英

Convert @RequestBody attribute containing entity ID to corresponding entity in Spring

Please, is it possible to achieve automatic conversion of request body attribute containing entity ID to corresponding JPA entity?

@Entity
public class Foo {
    @Id
    private Long id;

    // getters and setters
}  

public class Bar {
    private Foo foo;

    // getters and setters
}

@Controller
public class Controller {

    @RequestMapping(path="/foo", method=RequestMethod.POST)
    public void convertFooAction(@RequestBody Bar bar) {
        // variable bar with foo attribute containing entity with corresponding ID
    }
}

Example JSON request body used in POST request:

{ "foo": 1 }

It should work in every case, whether the @RequestBody class is @Entity or not.

Thanks for any advice.

We can make use of @JsonDeserialize strategy to achieve it like this :

Define BarDeserializer class :

public class BarDeserializer extends JsonDeserializer<Bar> {



    @Override
    public Bar deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
         JsonNode node = p.getCodec().readTree(p);
            int id = (Integer) ((IntNode) node.get("foo")).numberValue(); 
         Bar bar= new Bar();
         Foo foo=new Foo();
         foo.setId(new Long(id));
         bar.setFoo(foo);
         return bar;
    }



}


@JsonDeserialize(using=BarDeserializer.class)
public class Bar {      

     private Foo foo;

    public Foo getFoo() {
        return foo;
    }

    public void setFoo(Foo foo) {
        this.foo = foo;
    }




}

Finally tweaking the HttpMessageConverters :

 @Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    @Bean
    public MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Bar.class,new BarDeserializer());
        objectMapper.registerModule(module);
        jsonConverter.setObjectMapper(objectMapper);
        return jsonConverter;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(customJackson2HttpMessageConverter());

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM