一对多关系中的外键始终为空 - Spring Boot Data with JPA [英] Foreign key is always null in one to many relation - Spring Boot Data with JPA
问题描述
我有两个实体类 Country
和 Language
具有双向一对多关系.
I have two entity classes Country
and Language
having bi-directional one to many relationship.
以下是实体类:
@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 控制器:
Below is my Rest controller:
@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:
I'm trying to save below JSON:
{
"name": "Ireland",
"code": "IRE",
"languages": [
{
"name": "Irish"
}
]
}
问题是语言(子)外键始终为空,但正在插入其他属性.我在 Language
类的属性 Country country
上使用了 @JsonIgnore
,因为它导致请求大小问题,因为我有另一个 API 获取 Country 的数据以及它的语言.
The problem is that the language (child) foreign key is always null but other properties are getting inserted. I have used @JsonIgnore
on property Country country
of Language
class because it was causing issues with request size as I have another API fetching data of Country along with its Languages.
请指导.
推荐答案
你可以这样:
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:不要忘记添加适当的构造函数.如果您正在执行这样的构造函数重载,则还必须添加默认构造函数:
PS : Don't forget to add appropriate constructors. Also it is mandatory to add a default constructor if you are doing constructor overloading like this :
public Country() {}
public Country(String name) {this.name = name }
这篇关于一对多关系中的外键始终为空 - Spring Boot Data with JPA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!