Hibernate Many to Many Mapping with Additional Column

hibernate

I need to have additional column in manytomany generated table as

there are 2 entities which are related with each other as many to many
(User ManytoMany Group)

@Entity
public class User {
    //other fields
    private Set<Group> groups = new HashSet<Group>(0);
}

@Entity
public class Group {
    //other fields
    private Set<User> users = new HashSet<User>(0);
}

So here it generates 3 tables in database as

table1 – User

table2 – Group

table3 – UserGroup

Now I need additional field in UserGroup table, so how to specify that and in which entity?

Additonal field will be

private boolean isThisUserIsGroupManager;

So that, i can get that user of this group is a group manager also.

Best Answer

Relationships do not have persistent attributes to set, only entities do have. That's why you need third entity between. It will have two @Id attributes and consequently @IdClass is needed, because identity is derived from Group and User:

@Entity
public class User {
    @Id int id;    
    @OneToMany(mappedBy = "user")
    private Set<GroupMemberShip> groupMemberShips;
    ...
}

@Entity
public class Group {
    @Id int id;
    @OneToMany(mappedBy = "group")
    private Set<GroupMemberShip> groupMemberShips;
    ...
}


@Entity
@IdClass(GroupMemberShipId.class)
public class GroupMemberShip {
    @Id @ManyToOne User user;

    @Id @ManyToOne Group group;

    private boolean isThisUserIsGroupManager;
    ...
}

public class GroupMemberShipId implements Serializable {
    int user;
    int group;
    ...
}
Related Topic