Need help with mapstruct mapping new it
How can I map a List of object present in object to another object list.
I have an object
public class ObjectA{
@Id
private Long id;
@OneToMany(mappedBy = "pool", fetch = FetchType.EAGER)
private List<Pool> pool;
}
public class Pool{
@Id
private Long id;
@OneToOne
@JoinColumn(name="student")
private Student student;
}
public class Student {
@Id
private Long id;
@Column(name="number")
private String number;
}
Now I want to map the the ObjectA to Simple ObjectB
public class ObjectB{
private Long id;
private List<String > number;
}
I have tried this
@Mapping(target = "number", source = "pool")
ObjectB map(ObjectA objectA);
Can someone please help and explain how can we do it
could you please look into this code. I changed the mapper class and added a method for mapping of number of student and number of ObjectB:
@Mapper
public interface ObjectMapper {
@Mapping(source = "id", target = "id")
@Mapping(target = "number", expression = "java(mapPoolToStringList(objectA.getPool()))")
ObjectB mapObjectAtoObjectB(ObjectA objectA);
default List<String> mapPoolToStringList(List<Pool> poolList) {
List<String> numberList = new ArrayList<>();
for (Pool pool : poolList) {
numberList.add(pool.getStudent().getNumber());
}
return numberList;
}
}
and the main class :
ObjectMapper mapper = Mappers.getMapper(ObjectMapper.class);
Student student1 = new Student(1L, "100");
Student student2 = new Student(2L, "200");
Student student3 = new Student(3L, "300");
Student student4 = new Student(4L, "400");
Pool pool1 = new Pool(1L, student1);
Pool pool2 = new Pool(2L, student2);
Pool pool3 = new Pool(3L, student3);
Pool pool4 = new Pool(4L, student4);
List<Pool> poolList = new ArrayList<>();
poolList.add(pool1);
poolList.add(pool2);
poolList.add(pool3);
poolList.add(pool4);
ObjectA objectA = new ObjectA();
objectA.setId(1L);
objectA.setPool(poolList);
ObjectB objectB = mapper.mapObjectAtoObjectB(objectA);
you can see that number of student object is in the objectB.