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

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

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

@Entity
@Component
public class Account {

    @Id
    private int accountNum;

    private String accountType;
    private int accountBalance;
    private String accountStatus;
@Entity
@Component
public class PersonalInfo {

    @Id
    private int accountNum;

    private String firstName;
    private String lastName;
    private String SSN;
    private String streetName;
    private String city;
    private String state;
    private String zipcode;
@RepositoryRestResource(collectionResourceRel="accounts",path="accounts")
public interface AccountsDB extends CrudRepository<Account, Integer>{

}
zvms9eto

zvms9eto1#

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

public interface AccountAndPersonalInfoService {
    void save(Account account, PersonalInfo personalInfo);
}
@Service
public class AccountAndPersonalInfoServiceImpl implements AccountAndPersonalInfoService {
    @Autowired
    private AccountsDB accountsDB;
    @Autowired
    private PersonalInfoDB personalInfoDB;

    @Override
    void save(Account account, PersonalInfo personalInfo) {
        if (account.getAccountNum() == personalInfo.getAccountNum()) {
            accountsDB.save(account);
            personalInfoDB.save(personalInfo);
        } else throw new IllegalArgumentException("The ids of the entities do not match.");
    }
}

相关问题