Additional attributes in many ways a lot of jpa

I have a little problem. I am trying to represent the relationship with pojo and jpa with the following display:

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 staging table contains a composite key id_a(PK), id_b(PK).

I would like my modeling to allow me: when I remove an item from table a or table b, it requires the intermediate table item to be removed by the waterfall

+3


source to share


1 answer


You must create an intermediate entity with this additional field and bidirectional references to both entities. This object must refer to base objects through a relationship @ManyToOne

, and base objects must refer to this intermediate object through a relationship @OneToMany

.

The attribute cascade

for links @OneToMany

must be set to CascadeType.REMOVE if you want this intermediate object to be automatically removed whenever you remove any of the connected elements.



Here's a rough 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;
}

      

+1


source







All Articles