将对象添加到另一种类型的列表

时间:2021-06-19 15:00:31

标签: java arraylist

我正在尝试返回从我的数据库中获得的记录。但是我在如何做到这一点上遇到了问题,因为我从数据库中检索到的数据与返回参数位于不同的类中。

public List<Record> getRecord(List<Request> requests) {
    List<Record> records = new ArrayList<>();
    for (Request request : requests) {
        Billing billing = billingRepository
                .findByBillingCycleAndStartDateAndEndDate(
                        request.getBillingCycle()
                        , request.getStartDate()
                        , request.getEndDate());
        if (billing != null) {
            // Need to add "billing" to "records" list here
        }
    }
    return records;
}

记录类

public class Record {

    private int billingCycle;
    private LocalDate startDate;
    private LocalDate endDate;
    private String accountName;
    private String firstName;
    private String lastname;
    private double amount;

public Record() {
}

//Getters and setters

Billing.class

public class Billing {

   private int billingId;
   private int billingCycle;
   private String billingMonth;
   private Double amount;
   private LocalDate startDate;
   private LocalDate endDate;
   private String lastEdited;
   private Account accountId;

public Billing() {

}

//Getters and setters

我能做什么?并请解释答案,以便我理解。好想学

1 个答案:

答案 0 :(得分:1)

您可以使用 DozerMapper。它将对象映射到具有相同名称属性的另一个对象,或者您必须在 dozer-mapping xml 中编写映射。

让我们来回答你的问题。在这里,您正在尝试将您的实体转换为另一个对象。

为此,您必须编写映射代码。它会是这样的,在使用实体对象之前将它们转换为另一个对象是很常见的做法。

Record toRecord(Billing billing) {
    if(billing == null) {
       return null;
    }
    Record record = new Record();
    record.setBillingCycle = billing.getBillingCycle();
    ...
    ...
    // other properties
    ...
    return record;

}