Spring @RequestBody REST服务在一些实体关系

时间:2017-09-18 08:54:26

标签: spring hibernate jackson spring-restcontroller spring-java-config

我正在休息和休眠。 我检查了stackoverflow这些链接,但他们没有解决我的问题!

Spring MVC 3.1 REST services post method return 415

415 Unsupported MediaType for POST request in spring application

HTTP Status 415 - Unsupported Media Type when doing POST

等等更多帖子..

当我在我的实体中有这种关系时,帖子和@RequestBody没有问题

University.java

public class University extends BaseEntity {

    private String name;
    private String address;
    private String telephon;


    @OneToMany(fetch = FetchType.LAZY, mappedBy = "university", cascade = CascadeType.ALL)
    @JsonManagedReference
    private List<Student> students=new ArrayList<>();
// setter an getter
}

Student.java

public class Student extends BaseEntity{

    @Column(name = "FIRST_NAME")
    private String firstName;

    @Column(name = "LAST_NAME")
    private String lastName;

    @Column(name = "SECTION")
    private String section;

    @ManyToOne
    @JoinColumn(name = "UNIVERSITY_ID",nullable = false)
    @JsonBackReference
    private University university;

// setter an getter
    }

但是当我将证书实体添加到我的关系中时如下

编辑:

Student.java

public class Student extends BaseEntity{

    @Column(name = "FIRST_NAME")
    private String firstName;

    @Column(name = "LAST_NAME")
    private String lastName;

    @Column(name = "SECTION")
    private String section;

    @ManyToOne
    @JoinColumn(name = "UNIVERSITY_ID",nullable = false)
    @JsonBackReference
    private University university;

   // added new relation
    @ManyToOne
    @JoinColumn(name = "certificateid",nullable = false)
    @JsonBackReference
    private Certificate certificate;


// setter an getter
    }

Certificate.java

public class Certificate extends BaseEntity{

     private String name;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "certificate")
    @JsonManagedReference
    private List<Student> students=new ArrayList<>();
    // setter an getter
}

在这种类型的关系中,我遇到 415错误。在某些帖子中,建议使用@ModelAttribute而不是@RequestBody,它会解决错误。但是由于this帖子,它表示在MVC中使用是合适的,而不是在休息模板中。

我的控制器api是:

   @RequestMapping(value = "/create3", method = RequestMethod.POST,consumes = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<University> create3( @RequestBody University model) throws Exception {
        return new ResponseEntity<University>(this.universityService.add(model), HttpStatus.OK);
    }

和我的配置类

@Configuration
@EnableTransactionManagement
@EnableWebMvc
public class moduleConfig extends WebMvcConfigurerAdapter {


    @Bean
    public ObjectMapper objectMapper(){
        ObjectMapper mapper = new ObjectMapper();

        Hibernate5Module module = new Hibernate5Module();
        module.configure(Hibernate5Module.Feature.FORCE_LAZY_LOADING, false);

        mapper.registerModule(module);

        //Some other configuration....

        return mapper;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        converters.add(new MappingJackson2HttpMessageConverter());
        super.configureMessageConverters(converters);
    }
//configure the output json format
//https://stackoverflow.com/questions/4823358/spring-configure-responsebody-json-format
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof AbstractJackson2HttpMessageConverter) {
                AbstractJackson2HttpMessageConverter c = (AbstractJackson2HttpMessageConverter) converter;
                ObjectMapper objectMapper = c.getObjectMapper();
                objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            }
        }

        super.extendMessageConverters(converters);
    }

@Bean
public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(this.jacksonBuilder().build());

    return converter;
}

public Jackson2ObjectMapperBuilder jacksonBuilder() {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();

    Hibernate5Module hibernateModule = new Hibernate5Module();

    hibernateModule.configure(Hibernate5Module.Feature.FORCE_LAZY_LOADING, false);

    builder.modules(hibernateModule);

    // Spring MVC default Objectmapper configuration
    builder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    builder.featuresToDisable(MapperFeature.DEFAULT_VIEW_INCLUSION);

    return builder;
}



@Bean
public ViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}



}

}

1.实体关系如何导致我的帖子方法出现问题?

2.我的代码中缺少什么才能正确完成?

任何帮助和想法表示赞赏。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

杰克逊在一个实体类上不支持多个@JsonBackReference而没有专门命名它们(每个相关都有一个默认名称)。

为每个关系设置一个特定名称,如:

@JsonManagedReference(value = "a_name")

@JsonBackReference(value = "a_name")

问题来自JSON(以及任何面向文档的数据)的格式,它不允许一个节点有多个父节点。