【发布时间】:2020-02-28 04:49:23
【问题描述】:
我正在使用 Spring + Hibernate JPAA。
我有一个实体:
A
id (PK)
Set<B> b;
otherProps…
B
id (PK)
String name; (unique)
otherProps…
并且有一个 M 到 M 表链接 A.id、B.id。
如果用户创建实体:
A.id = 0
A.b.id = 0
A.b.Name = "Admin";
它会保存,但会在 B 表中创建一个新条目。将 B 视为系统定义的“角色”表,它不应该改变。所以我希望它重新使用 Admin 并自动填充 id。该对象来自 REST api……在这种情况下,调用者是否应该知道 ID 和名称?或者他们应该能够通过 id 或 Name 填充?
如何处理这种情况?还是去掉id,取名字为PK会更好?
编辑:澄清...
用户实体 角色实体 UserRole 表与 User.Id、Role.Id M2M 关系。
角色表包含: 1 位用户 2 管理员 3 超级用户
那是我定义的固定表。不允许调用者添加角色。
所以如果User1是User,那么M2M表1,1中就会有一个条目。
现在,想象一下如果有人传入一个角色为“用户”的新用户对象 User2。就像现在一样,它在 Roles id=4 value=User (重复条目)中创建一个条目,并在 M2M 表中创建一个 1,4,其中预期行为是 1,1,即重用现有的“用户”角色。
基本上,我想调用者知道用户 id 是有意义的,但我不确定调用者知道角色 id 是否有意义?似乎他们会知道可能的角色。有点像枚举类型的行为?
@实体 @Table(name="客户") 公共类客户{
@ApiModelProperty(notes="Id of the customer.", required=true, value="100000")
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long customerId;
@NotNull
@Size(min=2, max=64)
@ApiModelProperty(notes="First name of the customer.", required=true, value="John")
private String firstName;
@NotNull
@Size(min=2, max=64)
@ApiModelProperty(notes="Last name of the customer.", required=true, value="Smith")
private String lastName;
@ManyToMany(cascade={ CascadeType.MERGE })
@JoinTable(name="CustomerRoles",
joinColumns={ @JoinColumn(name="CustomerId") },
inverseJoinColumns={ @JoinColumn(name="RoleId") }
)
private Set<Role> roles = new HashSet<>();
public Long getCustomerId() {
return this.customerId;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<Role> getRoles() {
return new ArrayList<Role>(this.roles);
}
@实体 @Table(name="角色") 公共类角色 {
@ApiModelProperty(notes="Id of the role.", required=true, value="1")
@Id
//@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long roleId;
@NotNull
@Size(min=2, max=64)
@ApiModelProperty(notes="Name of the role.", required=true, value="Admin")
private String name;
@ManyToMany(mappedBy = "roles")
private Set<Customer> roles = new HashSet<Customer>();
public Long getRoleId() {
return this.roleId;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
【问题讨论】: