Reputation: 602
I have 2 tables, Person and phone and they have a one to one relationship.
**Person**
person_id
name
**Phone**
phone_id
person_id -- foreign key and not null constraint
number
This is how I have mapped it:
Person{
@Column(name="person_id")
Long personId;
@OneToOne(mappedBy = "person", cascade = CascadeType.ALL,
fetch = FetchType.EAGER, optional = false)
private Phone phone;
public void setPhone(Phone phone) {
this.phone = phone;
phone.setPerson(this);
}
}
Phone{
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="person_id")
private Person person;
}
I am using spring data. So when I try to save a Person like so, it gives me DataIntegrityViolationException - HsqlException: integrity constraint violation: NOT NULL check constraint table: "PHONE" column: "person_id"
Person person = new Person();
Phone phone = new Phone();
//populate phone and person properties.
person.setPhone(phone);
repository.save(person);
repository.flush();
When I remove the not null constraint from the table and execute the same insert, then it passess successfully.
Upvotes: 0
Views: 477
Reputation: 3410
You never supplied a value for person_id from your entity. My guess is that you meant to use person_id on your person field from Phone, but mistyped as phone_id.
In this case, the null constraint error is appropriate.
Edited: Alternatively, your ID field on Person is missing both the @Id and @GeneratedValue annotations which could also explain the null constraint violation.
Upvotes: 1