Which annotation is used to define a many-to-one relationship in JPA?

Java MCQ: Which annotation is used to define a many-to-one relationship in JPA?

a) @OneToMany
b) @ManyToOne
c) @OneToOne
d) @ManyToMany

Answer:

b) @ManyToOne

Explanation:

The @ManyToOne annotation is used to define a many-to-one relationship in JPA. This type of relationship means that many instances of an entity can be associated with one instance of another entity. The @ManyToOne annotation is typically used in the entity that holds the foreign key in the relationship.

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 Employee entity has a many-to-one relationship with the Department entity, meaning that multiple employees can belong to the same department. The foreign key column is specified using the @JoinColumn annotation.

Many-to-one relationships are common in database schemas and are easily represented in JPA using the @ManyToOne annotation.

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