Junior — Middle
Explain what the ForeignKey concept means in the context of relational databases.
sobes.tech AI
Answer from AI
ForeignKey is a field in one table of a relational database that references the primary key of another table. It ensures the relationship between records of different tables and maintains data integrity.
For example, there is an Orders table with a customer_id field that references the id field in the Customers table. This means each order is linked to a specific customer.
In Java, when working with ORM (e.g., Hibernate), foreign keys are usually modeled using annotations:
@Entity
public class Order {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "customer_id")
private Customer customer;
// getters and setters
}
Thus, ForeignKey helps organize relationships between tables and ensures data consistency in the database.