I have two entity classes Country
and Language
having bi-directional one to many relationship.
Below are the entity classes:
@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
}
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
}
I'm trying to save below JSON:
{
"name": "Ireland",
"code": "IRE",
"languages": [
{
"name": "Irish"
}
]
}
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.
Please guide.
You can do it in this way :
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 : 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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With