include into Lombok ToString field from another object

江枫思渺然 提交于 2019-12-23 18:42:32

问题


I have this POJOs

//@ToString(of = { "id", "name", "employee.id - not working" })
@ToString(of = { "id", "name", "employee - working" })
public class Company {

    private int id;
    private String name;

    @OneToMany(mappedBy="company")
    private Set<Employee> employee;
}

public class Employee{

    private int id;
    private String name;

    @ManyToOne
    private Company company;
}

how can I print just id from object employee? I do not want to print whole object employee, just one field.

Thank you


回答1:


You have several options.

  1. Write a method in Company which serialises the employee set as you like, then ask Lombok to exclude "employee" and to use your getter instead. This is no good if you don't like the ugliness of having a redundant field (see below).
  2. Write a custom toString method for Company. This is no good if you want to stick with a Lombok solution.
  3. Set ToString of Employee to use only id. This is no good if you want to print the rest of the Employee fields elsewhere.

An example of approach (1):

@ToString(of = {"id", "name", "employeeIdList"})
public class Company {

    private int id;
    private String name;

    @OneToMany(mappedBy="company")
    private Set<Employee> employee;

    private Set<Integer> employeeIdList; // unused field
    private Set<Integer> getEmployeeIdList() {
            // Return a set of employee ids only
            return employee.stream()
                .map(e -> e.getId()).collect(Collectors.toSet());
    }
}

Note that you need to have the field in order for Lombok to recognise the getter. However, the field itself is never used. I admit, this is ugly, albeit partially mitigated by both fields being private.

An example of approach (2):

public class Company {

    private int id;
    private String name;

    @OneToMany(mappedBy="company")
    private Set<Employee> employee;

    @Override
    public String toString() {
            String ids = "";
            for (Employee e : employee) {
                if (! ids.isEmpty())
                    ids += ", ";
                ids += e.getId();
            }
            return "Company(id="+id+", name="+name+", employees=["+ids+"])";
    }
}


来源:https://stackoverflow.com/questions/42649564/include-into-lombok-tostring-field-from-another-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!