【发布时间】:2019-02-07 15:25:53
【问题描述】:
我有两个实体类 Country 和 Language 具有双向一对多关系。
以下是实体类:
@Entity
@Table(name = "COUNTRY")
public class Country {
@Id
@GeneratedValue
@Column(name = "COUNTRY_ID")
private Long id;
@Column(name = "COUNTRY_NAME")
private String name;
@Column(name = "COUNTRY_CODE")
private String code;
@JacksonXmlElementWrapper(localName = "languages")
@JacksonXmlProperty(localName = "languages")
@OneToMany(mappedBy = "country", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
List<Language> languages;
// getters and setters
}
还有……
@Entity
@Table(name = "LANGUAGE")
public class Language {
@Id
@GeneratedValue
@Column(name = "LANGUAGE_ID")
private Long id;
@Column(name = "LANGUAGE_NAME")
private String name;
@ManyToOne
@JoinColumn(name = "COUNTRY_ID")
@JsonIgnore
private Country country;
//getters and setters
}
下面是我的 Rest 控制器:
@RestController
@RequestMapping("/countries")
public class CountryRestController {
private final ICountryRepository iCountryRepository;
@Autowired
public CountryRestController(ICountryRepository iCountryRepository) {
this.iCountryRepository = iCountryRepository;
}
@PostMapping("/country")
public ResponseEntity<?> postCountryDetails(@RequestBody Country country) {
Country savedCountry = this.iCountryRepository.save(country);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(savedCountry.getId()).toUri();
return ResponseEntity.created(location).build();
}
//other methods
}
我正在尝试保存以下 JSON:
{
"name": "Ireland",
"code": "IRE",
"languages": [
{
"name": "Irish"
}
]
}
问题在于语言(子)外键始终为空,但正在插入其他属性。我在Language 类的Country country 属性上使用了@JsonIgnore,因为它会导致请求大小出现问题,因为我有另一个API 正在获取Country 及其语言的数据。
请指导。
【问题讨论】:
标签: json rest spring-boot spring-data-jpa one-to-many