我有两个实体类Country
and 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
}
And...
@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
}
下面是我的休息控制器:
@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"
}
]
}
问题是语言(子)外键始终为空,但正在插入其他属性。我用过@JsonIgnore
财产上Country country
of Language
类,因为它导致请求大小问题,因为我有另一个 API 获取国家/地区及其语言的数据。
请指导。
你可以这样做:
Country newCountry = new Country(country.getName());
ArrayList < Language > langList = new ArrayList<>();
for (Language lang : country.getLanguages()) {
langList.add( new Language(language.getName(), newCountry ) ) ;
}
newCountry.setLanguages( langList );
iCountryRepository.save(newCountry);
PS:不要忘记添加适当的构造函数。
如果您要像这样进行构造函数重载,则还必须添加默认构造函数:
public Country() {}
public Country(String name) {this.name = name }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)