What is the role of the @JoinColumn annotation in JPA?

Java MCQ: What is the role of the @JoinColumn annotation in JPA?

a) It defines a foreign key column in a table
b) It maps a field to a database column
c) It specifies a named query
d) It defines the table name

Answer:

a) It defines a foreign key column in a table

Explanation:

The @JoinColumn annotation in JPA is used to define a foreign key column in a table. This annotation is typically used in associations like @ManyToOne, @OneToMany, @OneToOne, and @ManyToMany to specify the column that joins the related entities.

Here’s an example:

@Entity
public class Employee {
    @Id
    private Long id;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;

    private String name;

    // Getters and setters
}

In this example, the @JoinColumn(name = "department_id") annotation specifies that the department_id column in the Employee table is a foreign key that references the Department entity.

The @JoinColumn annotation provides a way to customize the foreign key column and manage relationships between entities in the database.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top