Category in Java Persistence with Spring Data and Hibernate

Definition

A Category is an entity that can be associated with multiple Item entities in a many-to-many relationship. This relationship allows a Category to be linked to several Items, and vice versa, enabling complex data models where entities can be interconnected in various ways.

Mapping Many-to-Many Relationships

Direct Many-to-Many Mapping

In Java Persistence API (JPA), a many-to-many association can be mapped using the @ManyToMany annotation on a collection. This is a straightforward approach where a join table in the database represents the association between the two entities.

@Entity
public class Category {
    // . . .
    @ManyToMany(cascade = CascadeType.PERSIST)
    @JoinTable(
        name = "CATEGORY_ITEM",
        joinColumns = @JoinColumn(name = "CATEGORY_ID"),
        inverseJoinColumns = @JoinColumn(name = "ITEM_ID")
    )
    private Set<Item> items = new HashSet<>();
    //  . . .
}

In this example, the Category entity is associated with the Item entity through a join table named CATEGORY_ITEM. The CascadeType.PERSIST is used to automatically persist the Item entities when a Category is persisted.

Bidirectional Many-to-Many Mapping

To enable bidirectional navigation, the Item entity can also be mapped to the Category entity:

@Entity
public class Item {
    // . . .
    @ManyToMany(mappedBy = "items")
    private Set<Category> categories = new HashSet<>();
    //  . . .
}

In this setup, the Item#categories collection is effectively read-only, and Hibernate will analyze the content of the Category#items side when storing data.

Using a Link Entity for Many-to-Many Relationships

Instead of using a direct many-to-many mapping, a more flexible approach involves using a link entity, such as CategorizedItem, to represent the association. This model is more extensible and allows for additional information to be stored in the link table.

CategorizedItem as a Link Entity

The CategorizedItem entity acts as a link between Category and Item, capturing additional information such as the timestamp and the user who created the link.

@Entity
@Table(name = "CATEGORY_ITEM")
@org.hibernate.annotations.Immutable
public class CategorizedItem {
    @Embeddable
    public static class Id implements Serializable {
        @Column(name = "CATEGORY_ID")
        private Long categoryId;
        @Column(name = "ITEM_ID")
        private Long itemId;
        // Constructors, equals, and hashCode
    }
    @EmbeddedId
    private Id id = new Id();
    @Column(updatable = false)
    @NotNull
    private String addedBy;
    @Column(updatable = false)
    @NotNull
    @CreationTimestamp
    private LocalDateTime addedOn;
    @ManyToOne
    @JoinColumn(name = "CATEGORY_ID", insertable = false, updatable = false)
    private Category category;
    @ManyToOne
    @JoinColumn(name = "ITEM_ID", insertable = false, updatable = false)
    private Item item;
    // Constructor and methods
}

This approach allows for additional columns in the join table, such as addedBy and addedOn, providing more context about the association.

Bidirectional Navigation with Link Entity

If bidirectional navigation is required, a @OneToMany collection can be mapped in Category and/or Item:

@Entity
public class Category {
    // . . .
    @OneToMany(mappedBy = "category")
    private Set<CategorizedItem> categorizedItems = new HashSet<>();
    //  . . .
}

This setup allows for navigation from both Category to Item and vice versa, using the CategorizedItem link entity.

Figures

[Figure 9.14](https://livebook.manning.com/book/java-persistence-with-spring-data-and-hibernate/chapter-9/142)

Figure 9.14 CategorizedItem is the link between Category and Item. Figure 9.14 CategorizedItem is the link between Category and Item.

This figure illustrates the CategorizedItem as the link between Category and Item, showing the structure of the link table with its composite key.

[Figure 9.15](https://livebook.manning.com/book/java-persistence-with-spring-data-and-hibernate/chapter-9/142)

Figure 9.15 CategorizedItem will be the link between Category and Item. Figure 9.15 CategorizedItem will be the link between Category and Item.

This figure demonstrates the use of CategorizedItem to represent the many-to-many association, highlighting the extensibility of this model.

FAQ (Frequently asked questions)

What is the role of CategorizedItem in the relationship between Category and Item?

What annotations are used to establish a many-to-many relationship in Java Persistence?