Hibernate Framework Hibernate Associations and Relationships 1 — Questions and Answers
Question 1: Which annotation is used to define a one-to-many relationship in Hibernate?
- @OneToOne
- @ManyToOne
- @OneToMany (Correct answer)
- @ManyToMany
Correct answer: @OneToMany
@OneToMany maps a collection field in the parent entity to multiple records in the child entity.
Question 2: In a bidirectional one-to-many relationship, which side is considered the 'owning side'?
- The 'one' side (parent entity)
- The 'many' side (child entity) with the foreign key (Correct answer)
- Both sides share ownership equally
- Whichever side is declared first
Correct answer: The 'many' side (child entity) with the foreign key
The 'many' side holds the foreign key column and is therefore the owning side responsible for the relationship in the database.
Question 3: Which annotation specifies the foreign key column name in a @ManyToOne relationship?
- @JoinTable
- @ForeignKey
- @JoinColumn (Correct answer)
- @Column
Correct answer: @JoinColumn
@JoinColumn specifies the name of the foreign key column in the owning entity's table that references the primary key of the related entity.
Question 4: What does the 'mappedBy' attribute in @OneToMany indicate?
- The name of the database join table
- The field in the owning entity that maps the relationship (Correct answer)
- The cascade type for the association
- The fetch strategy for loading child entities
Correct answer: The field in the owning entity that maps the relationship
'mappedBy' tells Hibernate that this side is the inverse (non-owning) side and points to the field in the child entity that owns the relationship.
Question 5: What is the default FetchType for a @OneToMany relationship in Hibernate?
- FetchType.EAGER
- FetchType.LAZY (Correct answer)
- FetchType.IMMEDIATE
- FetchType.SELECT
Correct answer: FetchType.LAZY
@OneToMany defaults to FetchType.LAZY, meaning the collection is not loaded from the database until it is explicitly accessed.
Question 6: Which annotation defines a many-to-many relationship in Hibernate?
- @ManyToOne
- @OneToMany
- @ManyToMany (Correct answer)
- @JoinTable
Correct answer: @ManyToMany
@ManyToMany maps a relationship where multiple records in one entity can be associated with multiple records in another entity.
Question 7: In a many-to-many relationship, which annotation is used to define the join table and its columns?
- @JoinColumn
- @JoinTable (Correct answer)
- @ManyToMany
- @RelationTable
Correct answer: @JoinTable
@JoinTable specifies the intermediate join table used by a many-to-many relationship, including the names of the join columns on both sides.
Which annotation is used to define a one-to-many relationship in Hibernate?