Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

supplementaire attributes in many to many relationship jpa

I have a little problem. I try to represent a relationship with pojo and jpa to the following mapping:

table A :
id_a (PK)
nom_a

table B :
id_b (PK)
nom_b

intermediate table :
id_a(PK), id_b(PK)
quantity

and my intermediate table contains a composite key id_a(PK), id_b(PK).

I would like my modeling allows me: when I delete an item from the table a or table b would require the element of the intermediate table is deleted by waterfall

like image 328
isom Avatar asked Jan 24 '26 21:01

isom


1 Answers

You should create an intermediate entity with this supplementary field and bidirectional references to both entities. This entity shall reference the base entities through the @ManyToOne relationship, and the base entities shall reference this intermediate entity through the @OneToMany relationship.

The cascade attribute for @OneToMany references should be set to CascadeType.REMOVE, if you want this intermediate entity to be automatically removed whenever you delete any of the connected items.

Here's the sample mapping (getters and setters omitted):

@Entity
public class FirstEntity implements Serializable {
    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(mappedBy = "firstEntity", cascade = CascadeType.REMOVE)
    private Set<IntermediateEntity> intermediates = new HashSet<>();
}

@Entity
public class SecondEntity implements Serializable {
    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(mappedBy = "secondEntity", cascade = CascadeType.REMOVE)
    private Set<IntermediateEntity> intermediates = new HashSet<>();
}

@Entity
public class IntermediateEntity implements Serializable {
    @Id
    @GeneratedValue
    private Long id;

    private Long quantity;

    @ManyToOne
    @JoinColumn(name = "first_entity_id")
    private FirstEntity firstEntity;

    @ManyToOne
    @JoinColumn(name = "second_entity_id")
    private SecondEntity secondEntity;
}
like image 128
Sergei Avatar answered Jan 26 '26 13:01

Sergei