0

I have @OneToMany relationship between two tables - Company:

@OneToMany( mappedBy = "company", cascade = CascadeType.ALL )
    private List< User > users = new ArrayList<>();

and User:

@ManyToOne
@JoinColumn( name = "companyId" )
private Company company;

The problem is, when I create a company with one user, everything is saved into db. A table company_users is created in db, but company id foreign key is not set in user table. It is still empty. I use spring CruDREpository also, but I don't think it could be a case in this example. Can you tell me why this FK is not set? This is a Postgres problem? I think the relationship was created in good way.

EDIT:

public CompanyDto createOrUpdate( final CompanyDto companyDto )
    {
        Company company = companyModelMapperWrapper.getModelMapper().map( companyDto, Company.class );
        Company saved = companyDao.save( company );
        if ( companyDao.exists( saved.getId() ) )
        {
            logger.info( "Company " + saved.getName() + " has been changed" );
        }

        return companyModelMapperWrapper.getModelMapper().map( saved, CompanyDto.class );
    }
Developus
  • 1,400
  • 2
  • 14
  • 50
  • Please add the code you are using to create the user. When you create a user you must set the company on it and save it. That should populate the FK column. – uncaught_exception Apr 20 '16 at 18:48
  • I think Hibernate should do it automatically? I have a simple crud, where I save company into db with user and I want to connect this entities automatically, Am I right? Btw. I updated post. – Developus Apr 20 '16 at 18:49

1 Answers1

0

Because you specified @OneToMany( mappedBy = "company") which means that the User is the owner of the relation.

And you must set the relation properly while persisting: In a bidirectional JPA OneToMany/ManyToOne association, what is meant by "the inverse side of the association"?

Community
  • 1
  • 1
gmaslowski
  • 774
  • 5
  • 13
  • Well I should remove this mapped from @OneToMany? – Developus Apr 20 '16 at 20:02
  • No. Just make sure that you're persisting `User` instance with `customer` field set in it. Which you probably should do in `map(companyDto, Company.class);` method. – gmaslowski Apr 20 '16 at 20:03
  • But in Company I have a list of users. I should put this company for every user in this list? I thought that Hibernate should do this on it own. – Developus Apr 20 '16 at 20:10
  • Ok, I understand. So if I have a company entity with list of users I have to set this company to every user from this list. It is not a good performance solution I think. – Developus Apr 20 '16 at 20:56