I'm having a very odd issue which I've been struggling with for many hours. I'm completely out of ideas, so any help is greatly appreciated.
I have two entities, Company and Campaign, where one company has many campaigns and one compaign has one company—a bidirectional one-to-many relationship.
The relevant code looks more or less like this (some parts have been left out for clarity):
Code:
public class Campaign
{
@ManyToOne
@JoinColumn(name="company_id")
public Company getCompany() { return company; }
public void setCompany(Company company) { this.company = company; }
}
public class Company
{
@OneToMany(mappedBy="company")
public Collection<Campaign> getCampaigns() { return campaigns; }
public void setCampaigns(Collection<Campaign> campaigns) { this.campaigns = campaigns; }
}
When I try to create a company and a campaign, save both, then link them together (using setCompany, for example), I get weird errors caused by violated foreign key constraints:
Quote:
Batch entry 0 insert into campaigns (company_id, name, id) values (NULL, Foo, 2118) was aborted.
ERROR: insert or update on table "campaigns" violates foreign key constraint "fkfd772163fb464619"
Detail: Key (id)=(2118) is not present in table "companies".
If I'm interpreting this correctly, then either Hibernate or Postgres is looking for a
Company with the ID of a
Campaign, which is causing an error because there is no company with the campaign's ID. I have no idea why this is happening…
There is one foreign key constraint in the "campaigns" table, and this is what it looks like:
Quote:
"fkfd772163c8bfc11b" FOREIGN KEY (company_id) REFERENCES companies(id)
which looks fine.
I have no idea what's going on here. Are my annotations correct? Did I forget an annotation here or there? Any hints that point me in the right direction are welcome. Thanks in advance!