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

Short Answer

To map a bidirectional one-to-many relationship, you:
1️⃣ Add a @OneToMany(mappedBy = "...") collection on the parent side.
2️⃣ Add a @ManyToOne reference to the parent on the child side.
This creates a two-way link between parent and child entities.

🔎 Detailed Explanation

🔹 Bidirectional means:

  • Both the parent and child know about each other.
  • The child has a reference to its parent → you can navigate parent → children and child → parent.

🔹 Mapping Example

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

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<ChildEntity> children = new ArrayList<>();
}

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

    @ManyToOne
    @JoinColumn(name = "parent_id") // foreign key in child table
    private ParentEntity parent;
}

✅ Here:

  • mappedBy="parent" on @OneToMany points to the ChildEntity.parent field → it tells JPA that the child’s parent field owns the foreign key.
  • The parent’s children collection is mapped as inverse side.

🔹 How it works in the database

  • The child table (ChildEntity) contains a parent_id column as a foreign key to the parent table (ParentEntity).
  • No join table → uses direct foreign key.

🔹 Synchronizing both sides
To keep object model consistent, you should manage both sides in your code:

ParentEntity parent = new ParentEntity();
ChildEntity child = new ChildEntity();

child.setParent(parent);
parent.getChildren().add(child);

⚠️ If you skip one side, your in-memory model may not match the database.

🔹 Key benefits of bidirectional mapping
✅ Allows navigation both from parent → children and child → parent.
✅ Great for using in queries or DTOs needing both directions.

📊 Quick Comparison

AspectBidirectional One-to-Many
Parent → children@OneToMany(mappedBy=...)
Child → parent@ManyToOne with @JoinColumn
SchemaForeign key in child table
NavigationBoth parent and child know each other

📌 Key Takeaways

✅ In bidirectional one-to-many, child owns the foreign key with @ManyToOne.
✅ Parent’s @OneToMany(mappedBy=...) defines the inverse side, pointing to the child’s parent field.
✅ Always synchronize both sides when adding/removing children → keeps in-memory model and DB consistent.

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

Leave a Reply

Your email address will not be published.