Suppose I have a table Customer
with these fields
- customer_id (PK)
- customer_name
- customer_surname
I also have some other tables that container a FK pointing to some customer.. For example Table1
has these fields:
- table1_id (PK)
- table1_col1
- table1_customer_id (FK references customer_id in
Customer
)
Table2
has these fields:
- table2_id (PK)
- table2_col1
- table2_customer_id (FK references customer_id in
Customer
)
The list of tables referencing the customers in the Customer
table can potentially grow and here is where I struggle with the JPA mapping.
I have an Entity Customer
like this:
@Entity
@Table(name = "customers")
public class Customer {
@Id
@Column(name = "customer_id")
private String customerId;
@Column(name = "customer_name")
private String customerName;
@Column(name = "customer_surname")
private String customerSurname;
// getters & setters
}
but now I don't know how to map the FKs for the other tables. How I would I map for example the Table1
?
@Entity
@Table(name = "table1)
public class Table1 {
@Id
@Column(name = "table1_id")
private Long table1Id;
@Column(name = "table1_col1)
private String table1Col1;
//private Long table1CustomerId; how can I make this a FK?
// getters & setters
}
The constraints are that each table (Table1
, .., TableN
) can have at most one customer, but each customer can be in any of the Table1
, .., TableN
.
Thank you
CodePudding user response:
Use this:
@ManyToOne(fetch = LAZY)
@JoinColumn(name = "table1_customer_id")
private Customer customer;