我正在实现一个银行应用程序,并且在我的数据库中有三个表(用户、帐户和帐户活动):
Account
和类的实现AccountActivity
如下所示:
@MappedSuperclass public abstract class AbstractDomain implements Serializable {
@Id @GeneratedValue
private long id = NEW_ID;
public static long NEW_ID = -1;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public boolean isNew() {
return id==NEW_ID;
}
}
@Table(name="ACCOUNT_ACTIVITY")
@Entity
public class AccountActivity extends AbstractDomain {
@Column(name="NAME")
private String Name;
@Column(name="XDATE")
private Date Date;
@Column(name="VALUE")
private double Value;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="ACCOUNTID")
private Account ACCOUNT;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="OTHERACCOUNTID")
private Account OTHERACCOUNT;
public String getName() {
return Name;
}
// ...
}
和:
@Table(name="ACCOUNT")
@Entity
public class Account extends AbstractDomain {
@Column(name="NAME")
private String Name;
@Column(name="XDATE")
private Date Date;
@Column(name="VALUE")
private double Value;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="USERID")
private User USER;
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private List<AccountActivity> AccountActivity = new ArrayList<AccountActivity>();
// ...
}
要将新帐户存储在我的数据库中,我使用以下命令:
public Account storeAccount(Account ac) {
User x = ac.getUser();
x = em.merge(x);
ac = em.merge(ac);
return ac;
}
它可以将新帐户存储在我的数据库中。我想实现这样的功能,即当将帐户活动信息添加到已保存的帐户时,该帐户将被更新,并且使用以下代码将添加的信息(帐户活动)级联到 AccountActivity 表:
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private List<AccountActivity> AccountActivity = new ArrayList<AccountActivity>();
当我测试这段代码时,我得到了错误:
java.sql.SQLException:违反完整性约束 - 没有父 FK670B7D019607336A 表:语句中的 ACCOUNT_ACTIVITY
有人可以帮我解决这个问题吗?
更新
我用这段junit代码进行测试:
public void testAddAccountActivities() {
User user = dummyPersistedUser();
User user2 = dummyPersistedUser();
Account account = getTestUtils().dummyEmptyAccount(user);
Account account2 = getTestUtils().dummyEmptyAccount(user2);
account=accountManager.storeAccount(account);
account2=accountManager.storeAccount(account2);
getTestUtils().fillAccounts(account, account2);
accountManager.storeAccount(account);
accountManager.storeAccount(account2);
assertEquals(2,accountManager.getAccount4Name(account.getName()).getAccountActivity().size());
assertEquals(2,accountManager.getAccount4Name(account2.getName()).getAccountActivity().size());
}
其中fillAccounts(account, account2)
只插入一些应添加到图表中的 AccountActivities。:
AccountActivity aa = new AccountActivity();
aa.setDate(new Date());
aa.setName("test activity");
aa.setAccount(a1);
aa.setValue(value);
aa.setOtherAccount(a2);
account.addAccountActivity(aa)