User1254
User1254

Reputation: 105

Map foreign key JPA

Suppose I have a table Customer with these fields

  1. customer_id (PK)
  2. customer_name
  3. customer_surname

I also have some other tables that container a FK pointing to some customer.. For example Table1 has these fields:

  1. table1_id (PK)
  2. table1_col1
  3. table1_customer_id (FK references customer_id in Customer)

Table2 has these fields:

  1. table2_id (PK)
  2. table2_col1
  3. 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

Upvotes: 1

Views: 2048

Answers (1)

Christian Beikov
Christian Beikov

Reputation: 16452

Use this:

@ManyToOne(fetch = LAZY)
@JoinColumn(name = "table1_customer_id")
private Customer customer;

Upvotes: 1

Related Questions