Non-Redundant Hibernate List-Mapping (OneToMany)



In a database there are “pastries”. A pastry has zero, one, or many allergens.

Hence I’m using a list in Pastry with @OneToMany relation. Now, with this way of managing the relations, we get redundant entries, as for each pastry a new entry with the same allergen is created:

Image 1

Our current solution looks like this:

A mapping-table in between those two database tables.

enter image description here

How can I achieve a non-redundant solution with direct references to the allergen elements from a list in the Pastry class? I googled a lot but sadly couldn’t find anything helpful.

Would look like this:
enter image description here

Regarding my comment on solution:
enter image description here

Answer

What you need is a called a JoinTable. Based on your schema definition this could work as a potential example:

@Data
@Entity(name = "Pastry")
@Table(name = "PASTRY")
public class Pastry {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany
    @JoinTable(
        name = "PASTRY_ALLERGEN",
        foreignKey = @ForeignKey(name = "FK_PASTRY_ALLERGEN_PASTRY"),
        inverseForeignKey = @ForeignKey(name = "FK_PASTRY_ALLERGEN_ALLERGEN"),
        joinColumns = @JoinColumn(name = "pastry_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "allergen_id", referencedColumnName = "id")
    )
    private Set<Allergen> allergens = new HashSet<>();

}

For the Pastry association and:

@Data
@Entity(name = "Allergen")
@Table(name = "ALLERGEN")
public class Allergen {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

}

For the Allergen association.

This mapping will in turn produce an intermediate table called PastryAllergens which will hold reference to the PK of the Pastry table and the PK of the Allergen table.



Source: stackoverflow