ManyToMany and superclass mapping problem

42 views Asked by At

I have a parent class of user with @mappedsuperclass annotation and classes of merchant, buyer, etc I want to make a role class and annotate @manytomany in that class to the parent class But this is not possible for me because it is not an entity. Is there another way that I can create a manytomany relationship to the parent class without creating a table of it in the DB?

I saw in previous answers of people that they changed to the @inheritance annotation but this creates a table of the parent class for me, which I don't want.

1

There are 1 answers

0
Ali Mnf On

you can use EmbeddedId and Embeddable class like below and made the relation by the subclasses:


@Entity
@Table(name = "user_role")
public class UserRole {
    @EmbeddedId
    private UserRoleKey id;

    @ManyToOne
    @MapsId("userId")
    private User user;

    @ManyToOne
    @MapsId("roleId")
    private Role role;

    // Other properties if needed

    }

@Embeddable
public class UserRoleKey implements Serializable {
    @Column(name = "user_id")
    private Long userId;

    @Column(name = "role_id")
    private Long roleId;

   
}

@Entity
@Table(name = "merchant")
public class Merchant extends User {
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<UserRole> userRoles = new HashSet<>();

    // Other merchant-specific properties, getters, and setters

    public void addRole(Role role) {
        UserRole userRole = new UserRole(this, role);
        userRoles.add(userRole);
        role.getUserRoles().add(userRole);
    }

    public void removeRole(Role role) {
        UserRole userRole = new UserRole(this, role);
        role.getUserRoles().remove(userRole);
        userRoles.remove(userRole);
        userRole.setUser(null);
        userRole.setRole(null);
    }
}