首页 > 解决方案 > 如何使用 Spring Boot Crudrepository 将数据插入到同一数据库中的 2 个表中?

问题描述

我希望能够为我的应用程序创建一个新帐户。我有一个代表一个实体的帐户类和另一个代表帐户个人信息的类。为了创建新帐户并将其保存在数据库中,我想将一些信息添加到帐户表中,并将一些信息添加到 PersonalInfo 表中,如下面的类中所述。如何使用 CrudRespository 接口执行此操作。据我了解,crudrepository 可以与数据库中的一个表进行交互。在我的示例中,这将是帐户。这很好,因为我的大部分检查和沟通都将与帐户表进行。但是当我创建一个新帐户时,我需要将要提供的数据添加到两个表中。我是否必须进行手动查询并将其作为一种方法添加到那里?

@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>{

}

标签: springdatabasespring-data-jpacrud

解决方案


只需为两个创建的实体分别创建一个存储库PersonalInfo并调用两个方法(分别属于两个不同的存储库)。save()

只需确保accountNum为这两个实体设置相同的 id ( )。

或者,您可以创建一个服务来为您执行此操作,如下所示:

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.");
    }
}

推荐阅读