我有 2 个分别命名为T_ACCOUNT和T_ACCOUNT_BENEFICIARY的数据库表。
这些表具有以下结构:
create table T_ACCOUNT (ID integer identity primary key, NUMBER varchar(9), NAME varchar(50) not null, CREDIT_CARD varchar(16), unique(NUMBER));
create table T_ACCOUNT_BENEFICIARY (ID integer identity primary key, ACCOUNT_ID integer, NAME varchar(50), ALLOCATION_PERCENTAGE decimal(5,2) not null, SAVINGS decimal(8,2) not null, unique(ACCOUNT_ID, NAME));
并且T_ACCOUNT表以一对多的关系绑定到T_ACCOUNT_BENEFICIARY表,这是图形表示:
所以这是第一个名为Account的类,它映射T_ACCOUNT表:
@Entity
@Table(name="T_ACCOUNT")
public class Account {
@Id
@GeneratedValue
@Column(name="id")
private Long entityId;
@Column(name="NUMBER")
private String number;
@Column(name="NAME")
private String name;
@OneToMany
@JoinColumn(name="ACCOUNT_ID")
private Set<Beneficiary> beneficiaries = new HashSet<Beneficiary>();
@Column(name="CREDIT_CARD")
private String creditCardNumber;
// GETTERS & SETTERS
}
这是映射T_ACCOUNT_BENEFICIARY表的Beneficiary类:
/**
* A single beneficiary allocated to an account. Each beneficiary has a name (e.g. Annabelle) and a savings balance
* tracking how much money has been saved for he or she to date (e.g. $1000).
*/
@Entity
@Table(name="T_ACCOUNT_BENEFICIARY")
public class Beneficiary {
@Id
@GeneratedValue
@Column(name="ID")
private Long entityId;
@Column(name="NAME")
private String name;
@Embedded
@AttributeOverride(name="value",column=@Column(name="ALLOCATION_PERCENTAGE"))
private Percentage allocationPercentage;
@Embedded
@AttributeOverride(name="value",column=@Column(name="SAVINGS"))
private MonetaryAmount savings = MonetaryAmount.zero();
正如您在帐户中看到的那样,我有一个受益人字段,它实现了一个可能的关系
@OneToMany
@JoinColumn(name="ACCOUNT_ID")
private Set<Beneficiary> beneficiaries = new HashSet<Beneficiary>();
我知道,在数据库上,这种关系是由 T_ACCOUNT_BENEFICIARY 表的ACCOUNT_ID字段实现的(因此T_ACCOUNT_BENEFICIARY表的多行可以具有相同的ACCOUNT_ID字段值,这意味着 T_ACCOUNT 表的单行可以是关联到多行T_ACCOUNT_BENEFICIARY表)。
正如您在前面的 sippet 中看到的,有@JoinColumn(name="ACCOUNT_ID")注释。
我的怀疑是由于我的T_ACCOUNT_BENEFICIARY表上有一个ACCOUNT_ID列,事实上:
create table T_ACCOUNT_BENEFICIARY (ID integer identity primary key, ACCOUNT_ID integer, NAME varchar(50), ALLOCATION_PERCENTAGE decimal(5,2) not null, SAVINGS decimal(8,2) not null, unique(ACCOUNT_ID, NAME));
但是此列似乎未映射到映射此T_ACCOUNT_BENEFICIARY表的受益人。
所以我的疑问是:@JoinColumn(name="ACCOUNT_ID")正在关系级别工作,对受益人实体(T_ACCOUNT_BENEFICIARY )映射的表的ACCOUNT_ID列执行连接操作,还是我遗漏了什么?这个连接究竟是如何执行的?
如果我的解释是正确的,我可以在实体级别工作并说将我的Account实体类的beneficiaries字段加入到插入到我的Beneficiary实体类中的新accountId字段并映射T_ACCOUNT_BENEFICIARY表的ACCOUNT_ID列吗?
肿瘤坏死因子