Anand
Anand

Reputation: 21310

Hibernate One to One mapping behaving as One to many

I am using a below One to one mapping between Account and Company.Company table has foreign key 'account_id'.Below is the code

@Entity
public class Company{
    ................
    @OneToOne
    @JoinColumn(name = "account_id")
    private Account account;
    ................
}

@Entity
public class Account{
    ................
    @OneToOne(mappedBy="account")
    private Company company;
    ...............
}

Now, above mapping means, For an Account, only one company can be related to it and vice-versa.

Now, Account table row would be inserted from somewhere else and save company would need to update one Account table column. Now, Save company request would contain company details and account id company relates to. On first request, company data is saved to company table with account id, but on subsequent requests for a particular account id, new row is getting inserted in company table even though only one company row should be created for a particular account id.

I was expecting some exception that only one company can be associated with a particular account. May i know the issue?

Upvotes: 0

Views: 146

Answers (1)

JB Nizet
JB Nizet

Reputation: 691625

When saving a new company having a given account, Hibernate will not check that no other company also has another account. And even if it checked you wouldn't have any guarantee, because several concurrent transactions should do that check in parallel, and then insert in parallel.

The only way to prevent that from occurring is to let the database itself prevent it, and that will happen if you let Hibernate generate the schema: there should be a unique constraint on the account_id column of the company table. If you generate your schema yourself, just make sure to create such a unique constraint.

Once the constraint exists, a transaction trying to insert a company with an account that is already associated to another company would get an exception from the database and rollback.

Upvotes: 2

Related Questions