如何使用spring boot crudepository将数据插入同一数据库中的两个表中?

zpf6vheq  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(552)

我希望能够为我的应用程序创建一个新帐户。我有一个account类,它表示一个实体,另一个类表示帐户的个人信息。为了创建新帐户并将其保存在数据库中,我想将一些信息添加到account表中,并将一些信息添加到personalinfo表中,如下所述。如何使用粗糙的界面来实现这一点。据我所知,crudrepository可以与数据库中的一个表进行交互。在我的例子中,那就是账户。这很好,因为我的大部分检查和通信都将与accounts表进行。但是,当我创建一个新帐户时,我需要将数据添加到两个表中。我必须手动查询并将其作为方法添加到其中吗?

  1. @Entity
  2. @Component
  3. public class Account {
  4. @Id
  5. private int accountNum;
  6. private String accountType;
  7. private int accountBalance;
  8. private String accountStatus;
  1. @Entity
  2. @Component
  3. public class PersonalInfo {
  4. @Id
  5. private int accountNum;
  6. private String firstName;
  7. private String lastName;
  8. private String SSN;
  9. private String streetName;
  10. private String city;
  11. private String state;
  12. private String zipcode;
  1. @RepositoryRestResource(collectionResourceRel="accounts",path="accounts")
  2. public interface AccountsDB extends CrudRepository<Account, Integer>{
  3. }
zvms9eto

zvms9eto1#

只需为创建一个存储库 PersonalInfo 调用两个 save() 方法(分别属于两个不同的存储库)分别使用两个创建的实体。
一定要设置相同的ID( accountNum )对于这两个实体。
或者,您可以创建一个服务来为您执行此操作,如下所示:

  1. public interface AccountAndPersonalInfoService {
  2. void save(Account account, PersonalInfo personalInfo);
  3. }
  1. @Service
  2. public class AccountAndPersonalInfoServiceImpl implements AccountAndPersonalInfoService {
  3. @Autowired
  4. private AccountsDB accountsDB;
  5. @Autowired
  6. private PersonalInfoDB personalInfoDB;
  7. @Override
  8. void save(Account account, PersonalInfo personalInfo) {
  9. if (account.getAccountNum() == personalInfo.getAccountNum()) {
  10. accountsDB.save(account);
  11. personalInfoDB.save(personalInfo);
  12. } else throw new IllegalArgumentException("The ids of the entities do not match.");
  13. }
  14. }
展开查看全部

相关问题