Spring REST,JSON“无法处理托管/返回引用'defaultReference'” 415不支持的媒体类型 [英] Spring REST, JSON "Can not handle managed/back reference 'defaultReference'" 415 Unsupported Media Type

查看:238
本文介绍了Spring REST,JSON“无法处理托管/返回引用'defaultReference'” 415不支持的媒体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从AngularJS前端使用 http:// localhost:9095 / translators 进行发布

我可以做一个GET,其响应如下所示:

  [{ 用户id:1, 名字: 约翰, 姓氏: Doe的, EMAILID: john.doe@inc.com, 语言: [{ languageId:1, 语言代码: GB, 源极:真}], 翻译:[{ translationId:3 的SourceID:1, sourceText: 你好, targetId:null,targetText:null,translationStatus:DUE}],userType:TRANSLATOR} 

发布下面的json时,我收到了错误响应



POST数据:

  {
姓:zen,
姓:cv,
emailId:email,
userType:TRANSLATOR,
语言:[{languageId:1,lang uageCode:gb,source:true}]
}



  {
时间戳:1422389312497
状态:415
错误:不支持的媒体类型
例外:org.springframework.web.HttpMediaTypeNotSupportedException
消息:不支持内容类型'application / json'
路径:/ translators
}

我确保我的控制器具有正确的Mediatype注释。

  @RestController 
@RequestMapping(/ translators)
public class TranslatorController {
@Autowired
private UserRepository库;

@RequestMapping(method = RequestMethod.GET)
public List findUsers(){
return repository.findAll();
}

@RequestMapping(value =/ {userId},method = RequestMethod.GET)
public User findUser(@PathVariable Long userId){
return repository.findOne(用户id);

$ b @RequestMapping(method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE,产生= MediaType.APPLICATION_JSON_VALUE)
public用户addTranslator(@RequestBody用户用户){
//translation.setTranslationId(null);
返回repository.saveAndFlush(user);
}

@RequestMapping(value =/ {translatorId},method = RequestMethod.PUT)
public User updateTranslation(@RequestBody User updatedUser,@PathVariable Long userId){
//updatedTranslation.setTranslationId(translationId);
返回repository.saveAndFlush(updatedUser);
}

@RequestMapping(value =/ {translatorId},method = RequestMethod.DELETE)
public void deleteTranslation(@PathVariable Long translationId){
repository .delete(translationId);






$ b经过一些研究并通过查看日志输出,意识到这是一个误导性的错误信息,问题实际上是在序列化/反序列化Json的过程中发生的问题



在日志文件中,我发现


2015-01-27 21:08:32.488警告15152 --- [nio-9095-exec-1]
.cjMappingJackson2HttpMessageConverter:未能评估
反序列化类型为[简单类型,类用户]:
java.lang.IllegalArgumentException:无法处理托管/返回
引用'defaultReference':返回引用类型(java.util.List)not
兼容托管类型(User)

这里是我的类User和class Translation(getter,setter,constructor等省略

pre code $ @ $实例
@Table(name =users)
public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column (name =user_id)
private long userId;

@Column(name =first_name)
private String firstName;

@Column(name =last_name)
private String lastName;

@Column(name =email_id)
private String emailId;
$ b @ManyToMany
@JoinTable(name =languages_users,joinColumns = {@JoinColumn(name =user_id)},
inverseJoinColumns = {@JoinColumn(name = lang_id)})
@JsonManagedReference
private List< Language> languages = new ArrayList< Language>();

@OneToMany(mappedBy =translator,fetch = FetchType.EAGER)
@JsonManagedReference
private List< Translation>译文;

@Enumerated(EnumType.STRING)
private UserType userType;
}

@Entity
@Table(name =translations)
public class Translation {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name =translation_id)
private long translationId;

@Column(name =source_lang_id)
private long sourceId;

@Column(name =source_text)
private String sourceText;

@Column(name =target_lang_id)
private long targetId;

@Column(name =target_text)
private String targetText;

@Enumerated(EnumType.STRING)
@Column(name =status)
私有TranslationStatus translationStatus;

@ManyToOne
@JoinColumn(name =translator_id)
@JsonBackReference
私人用户翻译器;

$ / code>

我的问题是:如何正确设置JsonManagedReference和JsonBackReference以上实体?我确实阅读了文档,并且根据错误消息我无法弄清楚这里有什么问题

解决方案

我解决了JsonManagedReference和JsonBackReference并将其替换为JsonIdentityInfo


I am trying to POST to http://localhost:9095/translators from an AngularJS front-end using Spring boot/Spring RestController backend.

I can do a GET and the response is like following:

[{"userId":1,"firstName":"John","lastName":"Doe","emailId":"john.doe@inc.com","languages":[{"languageId":1,"languageCode":"gb","source":true}],"translations":[{"translationId":3,"sourceId":1,"sourceText":"Hello","targetId":null,"targetText":null,"translationStatus":"DUE"}],"userType":"TRANSLATOR"}

When I post the below json, I get the error response

POST data:

{
                    firstName: "zen",
                    lastName: "cv",
                    emailId: "email",
                    userType: "TRANSLATOR",
                    languages : [{languageId:1,languageCode:"gb",source:true}]
}

Error:

{
timestamp: 1422389312497
status: 415
error: "Unsupported Media Type"
exception: "org.springframework.web.HttpMediaTypeNotSupportedException"
message: "Content type 'application/json' not supported"
path: "/translators"
}

I have made sure that my controller has correct Mediatype annotation.

@RestController
@RequestMapping("/translators")
public class TranslatorController {
    @Autowired
    private UserRepository repository;

    @RequestMapping(method = RequestMethod.GET)
    public List findUsers() {
        return repository.findAll();
    }

    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    public User findUser(@PathVariable Long userId) {
        return repository.findOne(userId);
    }

    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public User addTranslator(@RequestBody User user) {
        //translation.setTranslationId(null);
        return repository.saveAndFlush(user);
    }

    @RequestMapping(value = "/{translatorId}", method = RequestMethod.PUT)
    public User updateTranslation(@RequestBody User updatedUser, @PathVariable Long userId) {
        //updatedTranslation.setTranslationId(translationId);
        return repository.saveAndFlush(updatedUser);
    }

    @RequestMapping(value = "/{translatorId}", method = RequestMethod.DELETE)
    public void deleteTranslation(@PathVariable Long translationId) {
        repository.delete(translationId);
    }
}

After some research and also by seeing log output, I realize that this is a misleading error message and the problem is in fact happening while serializing/deserializing Json

In log file, I find

2015-01-27 21:08:32.488 WARN 15152 --- [nio-9095-exec-1] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate deserialization for type [simple type, class User]: java.lang.IllegalArgumentException: Can not handle managed/back reference 'defaultReference': back reference type (java.util.List) not compatible with managed type (User)

Here is my class User and class Translation (getter, setter, constructor etc. omitted for brevity)

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Column(name = "user_id")
    private long userId;

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

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

    @Column(name = "email_id")
    private String emailId;

    @ManyToMany
    @JoinTable(name = "languages_users", joinColumns = { @JoinColumn(name = "user_id")},
            inverseJoinColumns = {@JoinColumn(name = "lang_id")})
    @JsonManagedReference
    private List<Language> languages = new ArrayList<Language>();

    @OneToMany(mappedBy = "translator", fetch = FetchType.EAGER)
    @JsonManagedReference
    private List<Translation> translations;

    @Enumerated(EnumType.STRING)
    private UserType userType;
}

@Entity
@Table(name = "translations")
public class Translation {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name = "translation_id")
    private Long translationId;

    @Column(name = "source_lang_id")
    private Long sourceId;

    @Column(name = "source_text")
    private String sourceText;

    @Column(name = "target_lang_id")
    private Long targetId;

    @Column(name = "target_text")
    private String targetText;

    @Enumerated(EnumType.STRING)
    @Column(name = "status")
    private TranslationStatus translationStatus;

    @ManyToOne
    @JoinColumn(name = "translator_id")
    @JsonBackReference
    private User translator;
}

My question is this: How can I correctly set JsonManagedReference and JsonBackReference for the above entities? I did read the doc. and I cannot figure out what is wrong here based on the error message

解决方案

I got it solved by getting rid of JsonManagedReference and JsonBackReference and replacing it with JsonIdentityInfo

这篇关于Spring REST,JSON“无法处理托管/返回引用'defaultReference'” 415不支持的媒体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆