如何使用Spring JPA DATA仅获取特定子实体及其具有特定值的父实体

问题描述

我的实体类在下面,

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"
    }
}
]}

解决方法

我认为您需要从CustomerAccountAccount类的双向链接,以及一个CustomerAccountRepository类,该类具有一个声明为findByCustomerFirstNameAndCustomerLastName的方法,该方法返回{{1} }链接回CustomerAccount

为什么您使用的方法不起作用-帐户存储库仅返回帐户对象(除非您添加JPQL并将返回对象映射到其他对象)。 Account 找到一个(/全部)AccountRepository.findByCustomerAccountsCustomerFirstNameAndCustomerAccountsCustomerLastame(一个或多个),它们的AccountCustomerAccountCustomer.firstName匹配用户提供的内容。 Customer.lastnameAccount仍然是一对多的关系,因此将包含CustomerAccount的所有CustomerAccount(在您的情况下,Viki和Noah)。>

,

我认为这里的要求是获取数据并对其进行处理。作为open projections的一部分,可以进行一些基本处理。但是,恐怕您在下面的第2、3和4点中预期的主要帐户和辅助帐户的处理将必须在服务层中完成。

  1. 获取所有帐户,
  2. 如果主要客户和次要客户都匹配,请同时记账,
  3. 如果主要客户匹配,则从帐户中删除次要客户,
  4. 如果次要客户匹配,则从帐户中删除主要客户。
,

您需要按客户类型订购并使用分页机制。如果您确实必须使用方法名称约定(我讨厌它,它不可读,并且由于方法重命名,每次查询更改都需要重新启动应用程序),该方法应该为findTopByCustomerAccountsCustomerFirstNameAndCustomerAccountsCustomerLastameOrderByCustomerAccountsCustomerTypeAsc

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...