我有以下实体和 DTO:
public class Customer {
private Long id;
private String name;
@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
private Set<Account> accounts = new HashSet<>();
// getter, setter, constructors
}
我正在尝试通过映射 customer.getAccounts().getBalance()
和 customer.getAccounts().getTransactions()
将此实体列表映射到以下 DTO,如下所示:
@Data
public class CustomerResponse {
private Long id;
private String name;
private BigDecimal balance;
private List<TransactionResponse> transactions;
public CustomerResponse(Customer customer, Set<Account> accounts) {
this.id = customer.getId();
this.name = customer.getName();
// ???
this.balance = accounts...
this.transactions = customer.getAccounts()...
}
}
但是我无法映射,我不知道我是否可以在下面的服务方法中映射它们:
public List<CustomerResponse> findAll() {
final List<CustomerResponse> customers = customerRepository.findAll().stream()
.map(customer -> new CustomerResponse(customer, customer.getAccounts())).toList();
return customers;
}
那么,我怎样才能为每个客户正确映射 balance
和 transactions
?
这里是其他实体(为简洁起见省略了@Id
和一些其他注释):
public class Account {
private Long id;
private BigDecimal balance;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id", referencedColumnName = "id")
private Customer customer;
@OneToMany(mappedBy = "account", cascade = CascadeType.ALL)
private Set<Transaction> transactions = new HashSet<>();
// code omitted
}
public class Transaction {
private Long id;
private LocalDateTime date;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "account_id", referencedColumnName = "id")
private Account account;
}