エンティティIDを含むリクエストボディ属性を対応するJPAエンティティに自動変換することは可能ですか?
@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
}
}
POSTリクエストで使用されるJSONリクエスト本文の例:
{ "foo": 1 }
@RequestBody
クラスがそうであるかどうかにかかわらず、すべての場合に機能するはず@Entity
です。
アドバイスありがとうございます。
@JsonDeserialize戦略を利用して、次のように実現できます。
BarDeserializerクラスを定義します:
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;
}
}
最後に、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());
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加