问题
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.
- 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).
- Write a custom toString method for Company. This is no good if you want to stick with a Lombok solution.
- 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