我有三个关系导致我的问题。
<code>
@Entity
@Table(name="area")
public class Area implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name="name")
private String name;
...................
}
@Entity
@Table(name="law_connection")
public class Connection implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(fetch=FetchType.LAZY,cascade = {CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
@JoinColumn(name="client")
private Client client;
@OneToMany(fetch=FetchType.LAZY,targetEntity=Area.class, cascade = {CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
@JoinColumn(name="areas")
private List<Area> areas;
……………………
}
@Entity
@Table(name=“worker”)
public class Worker implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name="firstName")
private String firstName;
@Column(name="lastName")
private String lastName;
@OneToOne(fetch=FetchType.LAZY,cascade = {CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
@JoinColumn(name="organisation")
private Organisation organisation;
@Column(name="status")
@Enumerated(EnumType.ORDINAL)
private WorkerState state;
@OneToMany(fetch=FetchType.LAZY,targetEntity=Area.class,cascade = {CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
@JoinColumn(name="areas")
private List<Area> areas;
………………..
}
</code>
数据库中发生了什么:
<code>
mysql> select * from area;
+------+-----------------------+------------+
| ID | name | areas |
+------+-----------------------+------------+
| 1601 | Unknown | NULL |
| 1602 | Someplace | NULL |
| 1603 | Someotherplace | NULL |
| 1604 | Someplace2 | NULL |
| 1605 | Someplace3 | NULL |
| 1606 | Someplace4 | NULL |
| 1607 | Someplace5 | NULL |
| 1608 | Someplace6 | NULL |
| 1609 | Someplace7 | NULL |
| 1610 | Someplace7 | 1652 |
| 1611 | Someplace8 | NULL |
+------+-----------------------+------------+
11 rows in set (0.00 sec)
</code
观察到只有一个物体指向一个区域,我在这里误解了什么?
我需要一个工人有很多区域和一个连接至少有一个我做错了
答案 0 :(得分:0)
您无法在两个单独的集合之间共享外部外键。你现在有&#34;区域&#34;区域中的列,表示Area是否在Connection.areas中,还表示Area是否在Worker.areas中。如果它在该列中有值,它将如何知道它与哪个集合有关? (当它尝试检索Worker.areas时,它只会查找所有区域行,其中&#34;区域&#34;列设置为特定的工作者&#34; id&#34; ...类似于Connection.areas )。
更好的选择是在Area中有单独的FK列,一个名为WORKER_ID,另一个名为CONNECTION_ID。这样,Area可以在Worker.areas中,也可以在Connection.areas中,并且关系将单独处理。