【发布时间】:2017-05-02 07:44:32
【问题描述】:
我正在尝试为此 SO question 实现用户角色团队组模型的 JPA 实体 POJO
这是架构的 ERD:
我无法弄清楚 JPA 中的实体模型。
这是我正在处理的一些代码
账户实体
@Entity
public class Account extends BaseEntity {
@Id
@GeneratedValue
private Long accountId;
private String username;
private String password;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
private boolean enabled;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "ACCOUNT_ROLE", joinColumns = @JoinColumn(name = "ACCOUNT_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID"))
private Set<Role> userRoles;
角色实体
@Entity
public class Role extends BaseEntity {
@Id
@GeneratedValue
private Long roleId;
private String roleName;
BaseEntity 只是带有@PrePersist 和@PreUpdate 的公共字段
例如,如何使用 Account 和 Roles 之间的连接将 Teams 添加到此处?
更新:
我能够使用以下代码获得所需的表结构:
帐户:
@Entity
public class Accounts extends BaseEntity {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
private String username;
private String password;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
private boolean enabled;
private boolean ldapManaged;
@OneToMany(mappedBy = "account", cascade = CascadeType.ALL, orphanRemoval = true)
private List<AccountsRoles> roles = new ArrayList<>();
组:
@Entity
public class Groups extends BaseEntity {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinTable(name = "ACCOUNTS_ROLES_GROUPS")
private List<AccountsGroups> accounts;
角色:
@Entity
public class Roles extends BaseEntity {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
private String roleName;
@OneToMany(mappedBy = "role", cascade = CascadeType.ALL, orphanRemoval = true)
private List<AccountsRoles> accounts = new ArrayList<>();
团队:
@Entity
public class Teams extends BaseEntity{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
private String name;
private String managerEmail;
private String teamLeadEmail;
private String distributionListEmail;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinTable(name = "ACCOUNTS_ROLES_TEAMS")
List<AccountsRoles> accounts;
帐户组:
@Entity
public class AccountsGroups implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@ManyToOne
private Accounts account;
@Id
@ManyToOne
private Groups group;
}
AccountsRoles:
@Entity
public class AccountsRoles implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@ManyToOne
private Accounts account;
@Id
@ManyToOne
private Roles role;
但是,我不确定如何在链条中导航。
例如我如何获得帐户 -> 角色 -> 团队 -> 组
【问题讨论】:
-
您不会在其他关系中引用某个连接表,因为连接表仅代表第一个关系。如果你想利用那里的数据,你可以发明一些其他实体来表示连接表。