Wednesday, November 30, 2016

How to quickly convert type of Spring Data (JPA) Page content...

Suppose you have the current dto class

public class AbcDto {

private Long id;
private String description;
private Timestamp creationDate;

[.......]

}

and the model/bean to send as response via REST service that returns the pagination instance of Abc instances....

public class AbcView {

private Long id;
private String descriptionInUpperCase;
private String creationDateTruncated;

[.......]

}

That you use the repository to asking for data within "Pageable" form...
So you could have something like this...

Page<AbcDto> tmp = abcDtoRepository.findAll(new PageRequest(page, size));

So you can quickly convert the content, preserving the Page instance details in this way:

Page<AbcView > returnList = tmp.map(new Converter<AbcDto, AbcView> () {
                    @Override
                    public AbcView convert(AbcDto v) {
                        return new AbcView(v.getId(), v.getDesciption().toUpperCase(),
                                sdf.format(v.getCreationDate()));
                    }
                });

Simply and quick...
I hope this help you....

Bye..

No comments:

Post a Comment