How to popular a list to DTO more simply

Asked

Viewed 527 times

-1

To show the list of a register in my system, I populate the query in a DTO as below. My question is: There is a simpler way to popular the query in the DTO list?

public List<ObjetoDTO> find(Query query) {

    @SuppressWarnings("unchecked")
    List<Object[]> queryResult = query.getResultList();
    List<ObjetoDTO> list = new ArrayList<>();

    if (queryResult.isEmpty() == false) {
        for (Object[] item : queryResult) {
            ObjetoDTO dto = new ObjetoDTO();
            dto.setId((Integer) item[0]);
            dto.setTitulo((String) (item[1]));
            dto.setDescricao((String) (item[2]));
            list.add(dto);
        }
    }
    return list;
 }
  • what version of JPA?

  • Sorry, I’m using Hibernate 5.4.16.Final, I couldn’t identify which JPA version Hibernate uses :/

  • tried it like this: List<ObjetoDTO> list = (List<ObjetoDTO>) query.getResultList();?

  • 1

    In this case, I had a java.lang.Numberformatexception: For input string: "id". Because my id is an Integer.

  • On the bench is like ? the field id? because the line that I passed you saw in several forum that works!

  • You can make the query itself already return the DTO: https://stackoverflow.com/a/45934668

  • In the bank is as SERIAL NOT NULL id.

Show 2 more comments

1 answer

0


You can try using Dozer!

Download the dependency if your project is in Maven.

<dependency>
    <groupId>net.sf.dozer</groupId>
    <artifactId>dozer</artifactId>
    <version>5.4.0</version>
</dependency>

Mapper mapper = new DozerBeanMapper();
ObjetoDto dto = mapper.map(queryResult, ObjetoDto.class);

Only in the case when I used I created the Dtos classes, I had the entities and the Dtos, so I passed the mapper.map(entidade.class, ObjetoDto.class);

For more details, visit their website http://dozer.sourceforge.net/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.