Search code examples
javahibernatejpamodeling

@ManyToMany extra column


I need to model a relationship between clients and promotions. We need the history about clients promotions score CLIENTS_PROMOTIONS_HISTORY and the current score CLIENTS_PROMOTIONS

DB modelling is fine but I'm finding too hard to model the Entities. I intend to use CLIENTS_PROMOTIONS table for relationship purposes only and so that the Clients can be aware of their promotions + current score on each promotion. But can't figure out where to store the current score.

Entities and Diagram:

@Entity
@Table(name = "CLIENTS")
@SecondaryTable(name = "CLIENTS_PROMOTIONS",
                pkJoinColumns = @PrimaryKeyJoinColumn(name = "ID_CLIENT"))
class Client {

    @Id
    @Column(name = "ID_CLIENT", nullable = false, unique = true)
    Long id;

    @OneToOne(cascade = CascadeType.ALL, optional = false)
    @JoinColumn(name = "ID_USER", nullable = false, unique = true)
    User user;

    @Column(name = "NAME", nullable = false)
    String name;

    @Column(name = "BIRTHDAY", nullable = false)
    Date birthday;

    @Column(name = "EMAIL", nullable = false)
    String email;

    @Column(name = "SEX", nullable = false)
    Character sex;

    @ManyToMany
    @JoinTable(name = "CLIENTS_PROMOTIONS", 
               joinColumns = @JoinColumn(name = "ID_CLIENT"),
               inverseJoinColumns = @JoinColumn(name = "ID_PROMOTION"))
    Set<Promotion> promotions;
}

-

@Entity
@Table(name = "PROMOTIONS")
class Promotion {

    @Id
    @Column(name = "ID_PROMOTION", nullable = false, unique = true)
    Long id;

    @Column(name = "ID_ESTABLISHMENT", nullable = false)
    Long establishmentId;

    @Column(name = "TITLE", nullable = false)
    String title;

    @Column(name = "LIMIT_SCORE", nullable = false)
    Long limitScore;

    @Column(name = "DESCRIPTION", nullable = false)
    String description;

    @Column(name = "REWARD", nullable = false)
    String reward;
}

my eer diagram


Solution

  • You will need to create an Entity for Client_Promotions and model @ManyToOne relationship of this Entity with the Promotion and Client entities, instead of a @ManyToMany.