spring - 如何使用 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>{
}
解决方案
只需为两个创建的实体分别创建一个存储库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.");
}
}
推荐阅读
- excel - Excel - 将表格转换为不同的格式
- r - 如何解决 Rscript 解析错误:过早的 EOF?
- ios - TabBar 的背景颜色没有使用 ESTabBarController 改变
- reactjs - 使用 mapDispatchToProps 将文本输入值从一个屏幕传递到另一个屏幕
- php - 基于通配符子域获取动态内容
- zend-framework3 - 如何呈现电子邮件正文
- php - 通过 PostgreSQL 数据库的 PhP 表单更改用户和密码问题
- scala - 将序列插入返回 NullPointerException 的数据帧
- c - Macbook上的Xcode 10-如何使用键盘快捷键评论/ * * /?
- java - IBM Websphere Application 服务器上的应用程序的 Kafka SSL 连接问题