我正在修改遗留数据库,我必须将一个表拆分为两个。有很多代码引用我的实体类,所以我想使用@SecondaryTable来避免弄乱所有项目。
假设我有一个像这样的员工表:
+---------------+
|Employee |
|---------------+
|employee_id |(pk)(ai)
|first_name |
|last_name |
|email_personal |
|email_work |
+---------------+
但现在每个员工都可以拥有3个,4个或5个电子邮件地址,因此我们不想在Employee表中创建更多列,而是将它们带到一个名为Email_Address的单独表中,如下所示:
+-----------------+
|Email_Address |
|-----------------+
|email_address_id | (pk)(ai)
|employee_id | (fk)
|email_address |
|description |
+-----------------+
以前的寄存器是这样的:
+---------------+---------------+---------------+-------------------+---------------+
| employee_id | first_name | last_name | email_personal | email_work |
|---------------+---------------+---------------+-------------------+---------------+
| 1 | John | Locke | john@personal.com | john@work.com |
+---------------+---------------+---------------+-------------------+---------------+
现在是这样的:
+---------------+---------------+---------------+
| employee_id | first_name | last_name |
|---------------+---------------+---------------+
| 1 | John | Locke |
+---------------+---------------+---------------+
+--------------------+---------------+-------------------+-------------------+
| email_address_id | employee_id | email_address | description |
|--------------------+---------------+-------------------+-------------------+
| 1 | 1 | john@personal.com | Personal |
+--------------------+---------------+-------------------+-------------------+
| 2 | 1 | john@work.com | Work |
+--------------------+---------------+-------------------+-------------------+
最后我的问题:如果我当前的实体类是这样的话,我可以使用@SecondaryTable来解决这个问题吗?:
@Entity
@Table(name = "Employee")
public class Employee implements java.io.Serializable {
@Id
@Column(name = "employee_id")
private Integer patientId;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email_personal")
private String emailPersonal;
@Column(name = "email_work")
private String emailWork;
.
.
.
}
答案 0 :(得分:2)
@SecondaryTable仅在主要和次要之间具有一对一关系时才有效。基本上,您声明您的1个对象存储在2个(或更多)表中。它是@Embeddable的补充,表示您的2(或更多)对象存储在1个表中。
如果您要重构遗留代码并且不想处理从1变为多个的所有地址实例,您可以将地址标记为“home”或“primary”,并让“getAddress()”返回曾经做过的家庭或小学。您将创建另一个getter(确保将其标记为@Transient,如果您使用getter定义),名为getAllAddresses(),它将返回List或Set定义。
TL; DR - 不,@ SecondaryTable不起作用,使用@OneToMany ......