Doubt middle table Hibernate ManyToMany

-1

I'm starting Hibernate and I have a problem that I can not solve. Let's say I have two ManyToMany related entities. In the intermediate table that creates hibernate I need to add one more field apart from the 2 primary keys of both tables, this I am not able to get it in any way, even in some places I read that it is impossible to do it ...

Thanks in advance!

    
asked by Miguel Duran 20.09.2018 в 14:19
source

1 answer

0

It's not impossible, no.

You have to create an intermediate entity that will represent the table in which, in your physical model, you will flatten that M: N relation and in which you will have the specific attributes of that relation and you will convert the M: N into two 1: N .

This is an example of me: I have an M: N relationship between the SeriesEdition entity and the EventSession entity. The detail is that for given an instance of championship (SeriesEdition), a session (EventSession) and a scoring system (PointsSystem), I need to save what multiplier points must be applied in that case (column ps_multiplier )

@Entity
@Table(name = "POINTS_SYSTEM_SESSION")
public class PointsSystemSession {

    @EmbeddedId
    private PointsSystemSessionPK id;

    @ManyToOne
    @MapsId("series_edition_id")
    @JoinColumn(name = "SERIES_EDITION_ID")
    private SeriesEdition seriesEdition;

    @ManyToOne
    @MapsId("session_id")
    @JoinColumn(name = "SESSION_ID")
    private EventSession eventSession;

    @ManyToOne
    private PointsSystem pointsSystem;

    @Column(name="ps_multiplier")
    private Float psMultiplier = 1.0f;

...
}

And just in case, although it does not necessarily have to be missing, this is the table that defines the key of the entity:

@Embeddable
public class PointsSystemSessionPK implements Serializable {

    private static final long serialVersionUID = -5431412749175457078L;

    @Column(name = "SESSION_ID")
    private Long sessionId;

    @Column(name = "SERIES_EDITION_ID")
    private Long seriesEditionId;

    public PointsSystemSessionPK() {
        super();
    }

    public PointsSystemSessionPK(Long sessionId, Long seriesEditionId) {
        this.sessionId = sessionId;
        this.seriesEditionId = seriesEditionId;
    }

...
}

I hope you find it useful

    
answered by 20.09.2018 / 15:12
source