Java.Hibernate.Middle.How do you map a unidirectional one-to-many relationship?

Short Answer

To map a unidirectional one-to-many relationship, you use @OneToMany on the “one” side without a corresponding mapping on the “many” side. You typically combine it with @JoinColumn to specify the foreign key column in the “many” table.

🔎 Detailed Explanation

🔹 Unidirectional means:

  • Only one side (the parent) knows about the relationship.
  • The child entity does not have any reference back to the parent → the relationship is not bidirectional.

🔹 Mapping Example

@Entity
public class ParentEntity {
    @Id
    @GeneratedValue
    private Long id;

    @OneToMany
    @JoinColumn(name = "parent_id") // foreign key in child table
    private List<ChildEntity> children = new ArrayList<>();
}

@Entity
public class ChildEntity {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
}

🔹 What happens in the database?

  • The child table (ChildEntity) gets a parent_id foreign key column.
  • But there’s no parent field in ChildEntity Java class.
  • The relationship is owned by ParentEntity only → hence unidirectional.

🔹 Key Points about @JoinColumn:
✅ Required in unidirectional @OneToMany → otherwise JPA creates a join table (not foreign key).
@JoinColumn(name = "parent_id") tells Hibernate to put the parent’s ID directly in the child table → more efficient than a join table.

🔹 Without @JoinColumn?
If you skip @JoinColumn, JPA uses a join table (like in many-to-many), which is less efficient for one-to-many.

Example:

@OneToMany
private List<ChildEntity> children; 

→ creates a join table like parententity_childentity(parententity_id, childentity_id).

📊 Comparison: Unidirectional vs. Bidirectional

AspectUnidirectional One-to-ManyBidirectional One-to-Many
Child knows parent?❌ No✅ Yes (mapped with @ManyToOne)
Simpler mapping?✅ Yes❌ Slightly more complex
NavigationOnly parent → childrenParent ↔ child

📌 Key Takeaways

✅ Use @OneToMany + @JoinColumn on the parent entity → simplest way to map unidirectional one-to-many.
✅ Avoids join tables → better performance and simpler schema.
✅ The child entity doesn’t need a reference back to the parent.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.