我正在尝试在User
和FileObject
类之间创建多对多关系,假设用户可以访问许多文件对象,并且文件对象可以被许多用户访问,并且可以访问 - 很多关系,因为一个用户可以拥有多个文件,但一个文件只能由一个用户拥有。这是我的代码:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
public int id;
public String firstname;
public String lastname;
public String publicAttributes;
public String privateAttributes;
@ManyToOne
private Department department;
@OneToMany(mappedBy = "user")
public List<Device> devices = new ArrayList<Device>();
@OneToMany(mappedBy = "userCreator")
public List <FileObject> fileOwned = new ArrayList <FileObject>();
@ManyToMany
@JoinTable(name="USER_FILE_ACCESS")
public List<FileObject> fileHasAccess = new ArrayList<FileObject>();
}
@Entity
public class FileObject {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
public int id;
String checksum;
@OneToMany(mappedBy = "fileObject")
public List<Policy> policies = new ArrayList<Policy>();
byte[] encryptedFileKey;
byte[] iv;
@ManyToOne
public User userCreator;
@ManyToMany
public List<User> listUserAccessor = new ArrayList<User>();
}
理论上它应该只创建一个连接表,即USER_FILE_ACCESS,但是当我运行脚本时,它会创建两个连接表,我不知道为什么。
以下是SQL命令的摘录:
show tables;
+------------------+
| Tables_in_cpabe |
+------------------+
| DEPARTMENT |
| DEVICE |
| FILEOBJECT |
| FILEOBJECT_USER |
| POLICY |
| SEQUENCE |
| USER |
| USER_FILE_ACCESS |
+------------------+
show columns from FILEOBJECT_USER;
+---------------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+---------+------+-----+---------+-------+
| FileObject_ID | int(11) | NO | PRI | NULL | |
| listUserAccessor_ID | int(11) | NO | PRI | NULL | |
+---------------------+---------+------+-----+---------+-------+
show columns from USER_FILE_ACCESS;
+------------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------+---------+------+-----+---------+-------+
| User_ID | int(11) | NO | PRI | NULL | |
| fileHasAccess_ID | int(11) | NO | PRI | NULL | |
+------------------+---------+------+-----+---------+-------+
如何使联接表只有一个表?
答案 0 :(得分:3)
如果你想要双向关系,那么:
@Entity
public class User {
@ManyToMany
@JoinTable(name="USER_FILE_ACCESS"
joinColumns=@JoinColumn(name="user_id"),
inverseJoinColumns=@JoinColumn(name="fileHasAccess_ID "))
public Set<FileObject> fileHasAccess;
@Entity
public class FileObject {
@ManyToMany
@JoinTable(name="USER_FILE_ACCESS"
joinColumns=@JoinColumn(name="fileHasAccess_ID"),
inverseJoinColumns=@JoinColumn(name="user_id"))
public Set<User> listUserAccessor;
<强>更新强>
尝试使用SEt而不是List。
您还可以尝试另一种双向选项。因此,在非拥有方面,您将映射如下:
@ManyToMany(mappedBy = "fileHasAccess")
public Set<User> listUserAccessor;
另外仔细检查列名称..我可能已经放了一些不同于你在db中的实际情况。