Sobes.tech
Junior — Middle

What is a foreign key and how is it used to ensure data integrity between tables?

sobes.tech AI

Answer from AI

A foreign key is a column or a set of columns in one table that references the primary key of another table. It is used to ensure referential integrity of the data, meaning it guarantees that the value of the foreign key corresponds to an existing value in the related table.

For example, there is an Orders table with a CustomerID field, which is a foreign key referencing the ID field in the Customers table. This guarantees that each order is associated with an existing customer.

In Java, when working with databases through ORM (e.g., Hibernate), the foreign key is defined using annotations:

@Entity
public class Order {
    @ManyToOne
    @JoinColumn(name = "customer_id")
    private Customer customer;
    // other fields and methods
}

Thus, the foreign key ensures data integrity by preventing the creation of records with non-existent references and maintaining the relationship between tables.