I have two entities in my Spring API with a OneToOne relationship: Customer and CustomerAddress (this is just a simplified example of the problem). Each of these entities have their own tables. Here is the simplified definition of the tables and the entities:
customer (
id uuid,
name string
)
customer_address (
customer_id uuid, // This is a FK that references customer
street string
)
@Entity
class Customer {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
UUID id;
@Column(name = "name")
String name;
CustomerAddress customerAddress;
}
class CustomerAddress {
@Id
@Column(name = "customer_id")
UUID id; // This should be the same id as the parent
@Column(name = "street")
String street;
}
I want to create a Customer with it’s related CustomerAddress and be able to persist CustomerAddress as cascade when I call .save() on the customer. I already tried different approaches but I got different errors, such as:
Resolved [org.springframework.orm.jpa.JpaSystemException: attempted to assign id from null one-to-one property
insert or update on table "..." violates foreign key constraint
How can I correctly set the association between these two entities in order to be able to correctly persist both of them in one save?
Following this tutorial from Thorben Janssen I was able to successfully save both entities in a OneToOne relation with one save. The final entities looked like this:
@Entity
class Customer {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
UUID id;
@Column(name = "name")
String name;
@OneToOne(mappedBy = "customer")
@Cascade(CascadeType.ALL)
CustomerAddress customerAddress;
}
class CustomerAddress {
@Id
@Column(name = "customer_id")
UUID id;
@Column(name = "street")
String street;
@MapsId
@JoinColumn(name = "customer_id")
@OneToOne
Customer customer;
}
And this is the code that I used to persist the customer:
var customer = new Customer("joe")
var customerAddress = new CustomerAddress("street 1")
customer.setCustomerAddress(customerAddress)
customerAddress.setCustomer(customer)
customerRepository.save(customer)