ManyToMany 和超类映射问题

问题描述 投票:0回答:1

我有一个带有 @mappedsuperclass 注释的用户父类以及商家、买家等类 我想制作一个角色类并将该类中的@manytomany注释到父类 但这对我来说是不可能的,因为它不是一个实体。 有没有另一种方法可以创建与父类的多对多关系,而无需在数据库中创建它的表?

我在人们之前的回答中看到他们更改为@inheritance注释,但这为我创建了一个父类的表,这是我不想要的。

java hibernate annotations many-to-many mappedsuperclass
1个回答
0
投票

您可以像下面一样使用EmbeddedId和Embeddable类,并通过子类建立关系:


@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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.