一对多关系中的外键始终为空 - Spring Boot Data with JPA

Paw*_*mar 4 rest json one-to-many spring-data-jpa spring-boot

我有两个实体类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
}
Run Code Online (Sandbox Code Playgroud)

和...

@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
}
Run Code Online (Sandbox Code Playgroud)

下面是我的休息控制器:

@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

}
Run Code Online (Sandbox Code Playgroud)

我正在尝试保存以下 JSON:

{
  "name": "Ireland",
  "code": "IRE",
  "languages": [
    {
      "name": "Irish"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

问题是语言(子)外键始终为空,但正在插入其他属性。我使用了类的@JsonIgnore属性Country countryLanguage因为它导致请求大小问题,因为我有另一个 API 获取 Country 及其语言的数据。

请指导。

Viv*_*sal 6

你可以这样做:

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);
Run Code Online (Sandbox Code Playgroud)

PS:不要忘记添加适当的构造函数。如果您正在执行这样的构造函数重载,则还必须添加默认构造函数:

public Country() {}

public Country(String name) {this.name = name } 
Run Code Online (Sandbox Code Playgroud)