How to map ArrayList data to an DTO - java

As per the requirement, I have parsed an XML file and set data into these two DTO classes:
public class DetailsDTO implements java.io.Serializable {
private String userid;
private String accountnum;
private Customer customer;
// setters and getters
public class Customer implements Serializable
{
private String street;
private String country;
// setters and getters
After adding data of the Customer class to DetailsDTO, I added this DetailsDTO to an ArrayList as shown:
List list = new ArrayList();
// and added these DetailsDTO class to an ArrayList
list.add(detailsDTO)
Now there is a Master DTO called as WholeDetails which consists of all variables defined in various DTO classes as shown.
class WholeDetails
{
private String userid;
private String accountnum;
private String street;
private String country;
}
Now, as you see, all the data is aviable within the ArrayList.
How can I extract the contents from ArrayList and map it to the WholeDetails?

You will have to do the mapping e.g.
List<DetailsDTO> list = new ArrayList<DetailsDTO>();
// and added these DetailsDTO class to an ArrayList
list.add(detailsDTO);
List<WholeDetails> wholeDTOList = new ArrayList<WholeDetails>();
for(DetailsDTO dto:list){
WholeDetails whole = new WholeDetails();
whole.setUserid(dto.getUserid());
whole.setAccountNum(dto.getAccountNum());
whole.setStreet(dto.getCustomer().getStreet());
whole.setCountry(dto.getCustomer().getCountry());
wholeDTOList.add(whole);
}
If you like it to be more short you could create an adapter class that maps the DetailsDTO to the WholeDetailsDTO and add the result object to the list

Related

Map collection to an object using mapstruct

How can I define following mapping using Mapstruct java bean mapping. The problem how do I map the List ( with just one element) in source class to TargetPhone class
Source classes
class Source{
private String name;
private int age;
**This list always contain one element
and I cannot change this behavior or structure of this class**
private List<Phone> phones;
}
class Phone{
private Long id;
private String phoneNumber;
private String phoneColor;
// getters and setters
}
Target classes
class Target{
private String myName; **-->should map to Source.name**
private int myAge; **-->should map to Source.age**
private TargetPhone targetPhone;
// getters and setters
}
class TargetPhone{
private Long myId; **-->should map to Source.phones[0].id**
private String myPhoneNumber; **-->should map to Source.phones[0].phoneNumber**
private String myPhoneColor; **-->should map to Source.phones[0].phoneColor**
// getters and setters
}
Your mapper should be defined as shown below.
#Mapper
public interface MyMapper {
#Mapping(source="name", target="myName")
#Mapping(source="age", target="myAge")
#Mapping(source="phones", target="targetPhone")
Target sourceToTarget(Source source);
#Mapping(source = "id", target = "myId")
#Mapping(source = "phoneNumber", target = "myPhoneNumber")
#Mapping(source="phoneColor", target="myPhoneColor")
TargetPhone phoneToTargetPhone(Phone phone);
default TargetPhone listPhonesToTargetPhone(List<Phone> phones){
return phoneToTargetPhone(phones.get(0));
}
}
Where the default method does the magic of mapping the first element of Phone list to TargetPhone.

Convert multiple List items inside a POJO to a new List in Java

I have a POJO populated with a list of items in a Controller (after a rest ajax submit). This is the structure of the model that is populated:
public class AllNamesDto {
private List<Long> id;
private List<String> firstName;
private List<String> LastName;
private List<Boolean> manualSubmit;
private List<String> program;
//getters setters
}
I would like to extract all the list items from the model above and store them individually into a model List, e.g. the following model:
public class AllNamesDtoList {
private long id;
private String firstName;
private String LastName;
private Boolean manualSubmit;
private String program;
//getters setters
}
So something like
List<AllNamesDtoList> allNamesDtoList = new ArrayList<>();
allNameDtoList.add(AllNamesDto.items);
I know the syntax isn't correct, just ruffing it in to show quickly what I am trying to accomplish. My goal is to create a proper list of items (since I couldn't figure out a way to send a LIST through ajax properly, just a sublist of items in one POJO) to iterate over and save to the db.
Any help is appreciated!
Assuming that in the lists the order is correct and they are all the same size:
First put a constructor with fields:
public AllNamesDtoList(long id, String firstName, String lastName, Boolean manualSubmit, String program) {
super();
this.id = id;
this.firstName = firstName;
LastName = lastName;
this.manualSubmit = manualSubmit;
this.program = program;
}
And then we take the size of one of the lists and create an IntStream to iterate on the indices
List<AllNamesDtoList> allNamesDtoList = new ArrayList<>();
IntStream.range(0, id.size()).forEach(index -> allNamesDtoList.add(new AllNamesDtoList(id.get(index), firstName.get(index), LastName.get(index), manualSubmit.get(index), program.get(index))));
and the allNamesDtoList list would be full.

Mapstruct mapping - String to List<String>

I am struggling to map a string object from source(Relation.class) and to a List of target(RelationListDTO.class) .
Relation.java
public class Relation {
private String name;
private String email;
private String completeAddress;
// getters and setters
}
RelationListDTO.java
public class RelationListDTO {
private String name;
private String email;
private List<Address> address;
// getters and setters
}
Address.java
public class Address{
private String street;
private String city;
// getters and setters
}
Mapper class
#Mapper
public interface RelationMapper {
#Mapping(source = "completeAddress", target = "address.get(0).city")
RelationListDTO relationToListDto(Relation relation);
}
But it is not working. Could anyone please help.
What you are trying to do using MapStruct is not possible. Because MapStruct doesn't work with run time objects. MapStruct only generated plain java code for mapping two beans. And I find your requirement is little unique. You have a list of Addresses but want to map only city from source object? You can still do like this
#Mapping( target = "address", source = "completeAddress")
RelationListDTO relationToListDto(Relation relation);
// MapStruct will know to use this method to map between a `String` and `List<Address>`
default List<Address> mapAddress(String relation){
//create new arraylist
// create new AddressObject and set completeAddress to address.city
// add that to list and return list
}
Not sure if this was possible at the time of the accepted answer but I had the same problem as you and ended up doing it this way.
#Mapper(imports = Collections.class)
public interface RelationMapper {
#Mapping(expression = "java(Collections.singletonList(relation.getCompleteAddress()))", target = "address")
RelationListDTO relationToListDto(Relation relation);
}

Return List type in JPA

I have DTO structure like :
public class ADto{
private String name;
private String id;
private List<BDto> bdtos;
//Created constructor using fields
}
public class BDto{
private String id;
private String code;
private List<CDto> cdtos;
//Created constructor using fields
}
public class CDto{
private String mKey;
private String mVal;
//Created constructor using fields
}
Used Spring MVC for fetching the data.
Below query is working perfectly fine and binding the data :
#org.springframework.data.jpa.repository.Query("select new pkg.ADto(id,name) from AEntity a where a.id=?1")
public ADto getAData(Long id);
How can I fetch the data for the list which is in turn composed of further list using the above method?
If you want to return DTOs instead on enitites, you need to provide mapping between DTOs and entities. With JPQL query, the only option is to provide that mapping in constructor of the resulting object. Therefore, you need to add a constructor to ADto, which accepts BEntities, and map all nested entities to dtos in that constructor. Or in more object oriented way, the new constructor will accept AEntity as the only argument.
This is how it could look like:
getAData() method in the repository (JPQL is slightly modified by adding a.bEntities to result):
#org.springframework.data.jpa.repository.Query("select new pkg.ADto(id,name, a.bEntities) from AEntity a where a.id=?1")
public ADto getAData(Long id);
New constructor in ADto:
public class ADto{
private String name;
private String id;
private List<BDto> bdtos;
public ADto(String id, String name, List<BEntity> bEntities) {
this.id = id; this.name = name;
this.bdtos = new ArrayList<>();
for (BEntity b : bEntities) {
BDto bdto = new BDto(b.id, b.code, b.cEntities);
/* you need to pass cEntities and map them again in the BDto
* constructor, or you may do the apping in ADto constructor
* and only pass mapped values to BDto constructor */
}
}
}
You have to enable eager fetch:
#OneToMany(mappedBy = "adto", fetch = FetchType.EAGER)
private List<BDto> bdtos;
Then you can fetch it like this i.e.:
ADto findById(Long id); // literally!

Mapping a single JSON object to three different JAVA classes?

Can any one help me out in this , i'm new to JSON . The problem is that i want to map a single json objects Keys values pair to three different java classes?
{"firstName":"Sasi","lastName":"Dunston","jobTitle":"Trainee","dateOfBirth":"13/09/1990","bloodGroup":"O+ve",
"listOfEmail":["dunston08#gmail.com","charles.gmail.com","ravi.gmail.com"],
"listOfURL":["www.google.com","www.gmail.com","www.facebook.com"],
"listOfFaxNo":[8888888888,1111111111,2222222222,3333333333],
"listOfOfficeNo":[9999999999,8888888888,7777777777,6666666666],
"listOfAddress":[{"streetName":"xxxxx","city":"yyyyy","zipCode":"5555555","state":"hhhhhhh"},
{"streetName":"xxxxx","city":"yyyyy","zipCode":"5555555","state":"hhhhhhh"}]
}
this is my json object i want to map it to three different classes
Class PersonDetail
{
firstName
lastName
jobTitle
dateOfBirth
bloodGroup
/* Getter Setter */ of the above attributes
}
class PersonContact extends PersonDetail
{
ArrayList<String> listOfEmail=new ArrayList<String>();
ArrayList<String> listOfURL=new ArrayList<String>();
ArrayList<String> listOfFaxNo=new ArrayList<String>();
ArrayList<String> listOfPhoneNo=new ArrayList<String>();
/* Getter Setter */ of the above attributes
}
class Address extends PersonContact
{
String streetName;
String city;
String zipcode;
String state;
/* Getter Setter */ of the above attributes
}
Not tested, but the you should be able to map your json to PersonContact using the following class definitions:
Class PersonDetail
{
protected String firstName;
protected String lastName;
protected String jobTitle;
protected String dateOfBirth;
protected String bloodGroup;
/* Getter Setter */ of the above attributes
}
class PersonContact extends PersonDetail
{
private ArrayList<String> listOfEmail;
private ArrayList<String> listOfURL;
private ArrayList<String> listOfFaxNo;
private ArrayList<String> listOfOfficeNo;
private List<Address> listOfAddress;
/* Getter Setter */ of the above attributes
}
class Address
{
private String streetName;
private String city;
private String zipcode;
private String state;
/* Getter Setter */ of the above attributes
}
Just use https://github.com/FasterXML/jackson-databind
The tutorial should enable you to map the same source to different java objects (classes)

Categories

Resources