嵌套实体建模

时间:2019-03-06 16:22:30

标签: hibernate spring-data-jpa

我是冬眠/ jpa的新手,我面临如何正确建模嵌套实体的困难,我的要求是, 用户->具有多个角色->每个角色具有许多权限

角色的每个权限都必须作为单独的行保留在表中。 并且,需要为用户及其角色提供单独的表;同样,用户的每个角色都需要作为单独的行保留在表中。 我写了以下内容;但这不允许我创建具有已定义角色的新用户...

@Entity
@Table(name = "users")
public class User implements Serializable {

    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(name = "UUID",strategy = "org.hibernate.id.UUIDGenerator")
    public UUID id;

    @Column(name = "username")
    public String name;

    @Column(name = "password")
    public String password;

    @OneToMany(cascade = CascadeType.ALL, mappedBy="user")
    @LazyCollection(LazyCollectionOption.FALSE)
    public List<UserRole> roles;
}

@Entity
@Table(name = "user_roles")
public class UserRole implements Serializable {

    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(name = "UUID",strategy = "org.hibernate.id.UUIDGenerator" )
    public UUID id;

    @ManyToOne
    @JoinColumn(name="username", nullable=false, referencedColumnName = "username")
    public User user;

    @Column(name = "role_name")
    public String roleName;

    @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
    @JoinColumn(name = "role_name", referencedColumnName = "role_name")
    public List<RolePermission> permissions;

}

@Entity
@Table(name = "roles_permissions")
public class RolePermission implements Serializable {

    @Id
    @Column(name = "role_name")
    public String roleName;

    @Id
    @Column(name = "permission")
    public String permission;
}

出现以下错误,

  

2019-03-06 21:25:22.643错误48896 --- [nio-8090-exec-3]   o.h.engine.jdbc.spi.SqlExceptionHelper:错误:重复的键值   违反唯一约束“ uk_40fvvy071dnqy9tywk6ei7f5r”详细信息:   密钥(role_name)=(所有者)已经存在。

1 个答案:

答案 0 :(得分:0)

在正确建模UserRole之后,它可以正常工作,下面是我为UserRole创建的新实体类,

@Entity
@Table(name = "user_roles")
public class UserRole implements Serializable {

    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(
            name = "UUID",
            strategy = "org.hibernate.id.UUIDGenerator"
    )
    public UUID id;

    @ManyToOne
    @JoinColumn(name="username", nullable=false, referencedColumnName = "username")
    public User user;

    @Column(name = "role_name")
    public String roleName;

    @ManyToMany
    @JoinTable(name = "roles_permissions",joinColumns = @JoinColumn(name = "role_name"))
    public List<RolePermission> permissions;

}