Search code examples
jhipsterprojectionmapstruct

JHipster EntityMapper interface (mapstruct): map a Spring projection interface


I've generated a new project with JHipster v4.6.0 generator and I'm using its EntityMapper interface to do the mapping between domain and DTO objects.

public interface EntityMapper <D, E> {
    public E toEntity(D dto);
    public D toDto(E entity);
    public List <E> toEntity(List<D> dtoList);
    public List <D> toDto(List<E> entityList);
}

I need to use the Spring projection to have a smaller domain and DTO objects, (I don't want all fields of the entity), so I've created an interface with only the getters of the fields I need, and I've created a method in the repository which retrive this interface type (following the Spring reference guide)

public interface ClienteIdENome {
    Long getId();
    String getNome();
}

@Repository
public interface ClienteRepository extends JpaRepository<Cliente,Long> {
    ClienteIdENome findById(Long id);  
}

The query findById retrieve a ClienteIdENome object with only id and nome fields.

Now, I would like to map this object in the following DTO:

public class ClienteIdENomeDTO implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    @NotNull
    @Size(max = 50)
    private String nome;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
}

So, I created the mapper interface:

@Mapper(componentModel = "spring", uses = {})
public interface ClienteIdENomeMapper extends EntityMapper<ClienteIdENomeDTO, ClienteIdENome> {

}

But Eclipse report to me an error in the EntityMapper interface for the method "public E toEntity(D dto)" with the message:

No implementation type is registered for return type it.andrea.ztest01.repository.ClienteIdENome.

Any help? Thanks a lot


Solution

  • Your ClienteIdENome is not really an entity. I would argue that you don't need to use the EntityMapper, but you need to define a one way mapper. From ClienteIdENome to ClienteIdENomeDTO.

    Your mapper needs to look like:

    public interface ClienteIdENomeMapper {
        ClienteIdENomeDTO toDto(ClienteIdENome entity);
        List <ClienteIdENomeDTO> toDto(List<ClienteIdENome> entityList);
    }
    

    I don't know JHipster, so I can't say what will mean using a mapper different than EntityMapper.