Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign key is always null in one to many relation - Spring Boot Data with JPA

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.

like image 829
Pawan Kumar Avatar asked Dec 23 '22 04:12

Pawan Kumar


1 Answers

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 } 
like image 123
Vivek Bansal Avatar answered Jan 13 '23 14:01

Vivek Bansal