Java.Hibernate.Medium.Explain the JOINED strategy.

Short Answer

The JOINED strategy maps each class in an inheritance hierarchy to its own table, linking them by foreign keys, and represents a more normalized approach compared to SINGLE_TABLE.

🔎 Detailed Explanation

🔹 In JOINED, each entity class — base and subclasses — has its own separate table in the database:

  • The base class table holds columns for base fields + the primary key.
  • Each subclass table holds only the subclass-specific fields + a primary key that joins to the base table’s primary key.

🔹 When you query a subclass, Hibernate joins the subclass table with the base table to build the full entity.

🔹 This strategy avoids having many nullable columns in a single wide table → better normalization.

🧑‍💻 Example

Entities:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Animal {
    @Id
    private Long id;
    private String name;
}

@Entity
public class Dog extends Animal {
    private String breed;
}

@Entity
public class Cat extends Animal {
    private boolean likesMilk;
}

Database tables created:

Table: animal
| id | name |

Table: dog
| id | breed |

Table: cat
| id | likes_milk |

🔹 How Hibernate Loads with JOINED

  • When you query Dog, Hibernate joins animal + dog on their shared primary key (id):
SELECT a.*, d.* FROM animal a
JOIN dog d ON a.id = d.id
WHERE ...

Hibernate assembles the full Dog object from data spread across these tables.

📊 Advantages & Disadvantages

Pros:

  • Better normalized schema → no columns with lots of NULLs.
  • Clean separation of shared vs. subclass-specific data.
  • Good when subclasses are very different or have many exclusive fields.

Cons:

  • Slower queries than SINGLE_TABLE → requires JOINs at runtime.
  • More complex schema → more tables, harder to inspect manually.

📌 Key Takeaways

✅ JOINED strategy maps each class to its own table, with subclass tables joined to the base table via primary keys.
✅ Improves normalization → no wasted NULL columns like SINGLE_TABLE.
✅ Comes with performance cost → requires SQL joins to load subclass instances.

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

Leave a Reply

Your email address will not be published.