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

后端 未结 3 700
一生所求
一生所求 2021-01-14 07:56

I have two entity classes Country and Language having bi-directional one to many relationship.

Below are the entity classes:



        
相关标签:
3条回答
  • 2021-01-14 08:34

    You can do it in this way also. Here it doesn't create new objects. In the same object which is parsing it creates the relationship in language objects.

    @PostMapping("/country")
    public Country postCountryDetails(@RequestBody Country country) {
    
        if( country.getLanguages().size() > 0 )
        {
            country.getLanguages().stream().forEach( countryItem -> {
                countryItem.setCountry( country );
            } );
        }
        return country;
    }
    
    0 讨论(0)
  • 2021-01-14 08:47

    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 } 
    
    0 讨论(0)
  • 2021-01-14 08:53

    Update the setter for languages in Country class to the below :

     public void setLanguages(List<Language> languages) {
            this.languages = languages;
            languages.forEach(entity -> entity.setCountry(this));
        }
    
    0 讨论(0)
提交回复
热议问题