问题描述
我的实体类在下面,
Account
accountId
balance
withdrawls
deposits
@OneToMany
List<CustomerAccount> customerAccounts
CustomerAccount
accountId
customerId
accountType
customerType (Primary/Secondary)
@OneToOne
Customer customer
Customer
accountId
customerId
firstName
lastName
假设用户使用 firstName = viki和 lastName =黑色
AccountRepository
findByCustomerAccountsCustomerFirstNameAndCustomerAccountsCustomerLastame(String firstName,String lastName);
即使一个被匹配,该查询也返回主要和次要对象。当名字和姓氏与主要匹配时,我不想返回次要。次要对象应为null,主要应具有响应。
但是它同时返回主要和次要的。 spring jpa数据中是否有方法仅返回 匹配的子实体以及父实体?
"CustAccnt":{
"Account":{
"balance":"","deposits":""
},"primary":{
"firstName":"Viki","lastName":"Black"
},"secondary":{
"firstName":"Noah","lastName":"Morgan"
}
}
]}
解决方法
我认为您需要从CustomerAccount
到Account
类的双向链接,以及一个CustomerAccountRepository
类,该类具有一个声明为findByCustomerFirstNameAndCustomerLastName
的方法,该方法返回{{1} }链接回CustomerAccount
。
为什么您使用的方法不起作用-帐户存储库仅返回帐户对象(除非您添加JPQL并将返回对象映射到其他对象)。 Account
找到一个(/全部)AccountRepository.findByCustomerAccountsCustomerFirstNameAndCustomerAccountsCustomerLastame
(一个或多个),它们的Account
与CustomerAccount
和Customer.firstName
匹配用户提供的内容。 Customer.lastname
与Account
仍然是一对多的关系,因此将包含CustomerAccount
的所有CustomerAccount
(在您的情况下,Viki和Noah)。>
我认为这里的要求是获取数据并对其进行处理。作为open projections的一部分,可以进行一些基本处理。但是,恐怕您在下面的第2、3和4点中预期的主要帐户和辅助帐户的处理将必须在服务层中完成。
- 获取所有帐户,
- 如果主要客户和次要客户都匹配,请同时记账,
- 如果主要客户匹配,则从帐户中删除次要客户,
- 如果次要客户匹配,则从帐户中删除主要客户。
您需要按客户类型订购并使用分页机制。如果您确实必须使用方法名称约定(我讨厌它,它不可读,并且由于方法重命名,每次查询更改都需要重新启动应用程序),该方法应该为findTopByCustomerAccountsCustomerFirstNameAndCustomerAccountsCustomerLastameOrderByCustomerAccountsCustomerTypeAsc