您可以使用@OneToMany關係而不是讓一個更簡單的設計中獲益。通過這種方式,您可以創建服務來管理文件權限,而不是依賴用戶服務或文件服務來執行此操作。
我建議是這樣的:
User.java
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Version
private Integer version;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
private List<FilePermissions> filePermissionsList= new ArrayList<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<FilePermissions> getFilePermissionsList() {
return filePermissionsList;
}
public void setFilePermissionsList(List<FilePermissions> filePermissionsList) {
this.filePermissionsList = filePermissionsList;
}
}
通知用戶有FilePermissions的列表。
你的FilePermission類應該是這樣的:
@Entity
public class FilePermissions {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Version
private Integer version;
@ManyToOne
private User user;
@OneToOne
private File file;
private Permission permission;
public FilePermissions() {
}
public FilePermissions(User user, File file, Permission permission) {
this.user = user;
this.file = file;
this.permission = permission;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public Permission getPermission() {
return permission;
}
public void setPermission(Permission permission) {
this.permission = permission;
}
}
通知的@ManyToOne關係返回給用戶,以及對文件類@OneToOne關係。在這裏你可以存儲用戶擁有什麼權限的細節,在這種情況下,我有一個枚舉。
文件類是直截了當:
@Entity
public class File {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Version
private Integer version;
private String name;
public File() {}
public File(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
您可以詳細看到這裏的解決方案:https://github.com/ccoloradoc/HibernateFilePermissionSample
你真的要更新用戶領域,保存文件中創建新用戶? –
要更改此行爲,您可以使用'@ JoinColumn'註釋的'insertable'和'updatable'標誌進行操作。 –
只需刪除'cascade'。這就夠了。 –