【发布时间】:2022-01-16 22:47:19
【问题描述】:
我需要获取特定客户 ID 和帐户 ID 的余额。
我有这两个 java 类。 (这两个类都有自己的 get 和 set 方法)
客户
public class Customer {
private int custid;
private String name;
private String address;
private String email;
private int pin;
private List<Account> accounts = new ArrayList<>();
public Customer(){
}
public Customer(int custid,String name, String address, String email, int pin, List<Account> accounts) {
this.custid = custid;
this.name = name;
this.address = address;
this.email = email;
this.pin = pin;
this.accounts = accounts;
}
帐户
public class Account {
private int accid;
private int sortCode;
private int accNumber;
private String accType;
private double currentBalance;
private List<Transaction> transactions = new ArrayList<>();
public Account(){
}
public Account(int accid,int sortCode, int accNumber, String accType, double currentBalance, List<Transaction> transactions) {
this.accid = accid;
this.sortCode = sortCode;
this.accNumber = accNumber;
this.accType = accType;
this.currentBalance = currentBalance;
this.transactions = transactions;
}
我有这两个客户服务和帐户服务类。 这是 CustomerService 和 Account Service 中的一个方法
客户服务
public Customer getCustomer(int id) {
return cList.get(id-1);
}
帐户服务
public Account getAccount(int accid) {
return aList.get(accid-1);
}
我需要像这样在我的 get 请求中使用两个参数。我在一个单独的班级中有以下内容。
@GET
@Path("/{customerID}/{accountID}")
@Produces(MediaType.APPLICATION_JSON)
public Customer getBalance(@PathParam("customerID") int cID,@PathParam("accountID") int aID ) {
//gets customer for CustomerServices and returns it
return customerService.getCustomer(cID);
}
如何退回给定客户 id 及其帐户 id 的余额?
【问题讨论】:
-
查看 DTO。您可以在回复中发回任何内容。根据 cID 和 accentID,您可以创建一个包含客户详细信息和帐户余额的自定义响应对象。另一种方法是将客户映射添加到 Account 实体中 - 这将为您提供基于 cID 和 accountID 的 Accountz+Customer 对象,但不确定这是否适合您的业务逻辑
-
我有
//Get specific customer from customers using id Customer c = customerService.getCustomer(cid); //Get a list of the accounts on that customer List<Account> accounts = c.getAccounts(); //Return the specific account from the array of accounts return accounts.get(aid-1);返回帐户,但我只想返回余额。我该如何反映? -
这就是 DTO 的用武之地。为例如创建一个类CustomerResponse 包含 Customer 类的所有字段和余额的附加字段。传入所有值并返回该 DTO(自定义类)。但是,如果您将客户映射添加到 Account 类中,那么您将获得特定的帐户 Account acc = repo.getAccount(aid) 并且 acc.getCustomer() 将为您提供客户。