我有一个实体类State
,它扩展了抽象类Location
并实现了它的抽象方法。当我在内容类型设置为Json的poster上发出PostMapping
请求时,我得到了一个不支持的媒体类型错误,如下所示:
"error:" Unsupported Media Type,
"trace": org.springframework.web.HttpMediaTpeNotSupportedException:Content type:'application/json;...
抽象类:
@MappedSuperclass
public abstract class Location {
@Id
@Column(name="id")
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
@Column(name = "long")
private String longitude;
@Column(name = " lat")
private String latitude;
public Location (){}
//assessors & mutators ommited with abstract methods
}
混凝土国家实体类别:
@Table(name="State")
public class State extends Location {
@Pattern(regexp = "[0-9]{5}")
private String sateCode;
@JsonManagedReference
@OneToOne(mappedBy="state",
cascade=CascadeType.All, fetch=FetchType.Lazy)
private City city = new City();
//constructors & other implementations omitted
@Override
public void setCity(String city){
this.city=city
}
public void setStateCode(String code){
this.stateCode = stateCode;
}
///getter omitted
}
混凝土城市实体类别:
@Table(name = "City");
public class City extends Location {
@JsonBackReference
@OneToOne(cascade={
CascadeType.DeTACH, CascadeType. MERGE})
@JoinColumn(name = "state_city_id")
private State state;
//constructors & other implementations omitted
@Override
public void setState(State state) {
this.state=state;
}
}
}
控制器:
@Controller
@RequestMapping(path = "location/destination")
public class LocationController{
@Autowired
@Qualifier("stateImpl")
private LocationService service;
@PostMapping(value = "/state", consumes = org.springframework.http.MediaType.APPLICATION_JSON_VALUE, produces = org.springframework.http.MediaType.APPLICATION_JSON_VALUE)
public void save( @Valid @RequestBody State s ,BindingResult theBindingResult,
HttpServletResponse r) throws IOException{
if(theBindingResult.hasErrors()) {
throw new InputException("Wrong data input!");
}
service.save(s);
r.sendRedirect("");
}
@GetMapping()
public ResponseEntity<Object>findAll(){
return new ResponseEntity<Object>(service.findAll(),HttpStatus.OK);
}
}
邮递员上的错误消息:
"status": 415,
"error": "Unsupported Media Type",
"trace": "org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8 not supportedrntat...'
当我更改State
实体类中的city
字段时,代码工作了,如下所示:
@Entity
@Table(name="State")
public State extends Location {
@JsonBackReference
@OneToOne(mappedBy="state",
cascade=CascadeType.All, fetch=FetchType.Lazy)
private City city = new City();
}
City
实体中的state
字段是这样的:
@Entity
@Table(name="City")
public class City extends Location {
@JsonManagedReference
@OneToOne(cascade={
CascadeType.DeTACH, CascadeType. MERGE})
@JoinColumn(name = "state_city_id")
private State state;
}
```.
Though I'm yet to understand what really happened behind the scenes.