使用Model Mapper映射并写入DTO列表

时间:2018-03-08 16:29:24

标签: java dto data-transfer-objects modelmapper

所以我成功地将一条记录写入由模型映射器创建的DTO,但是如果我想创建一个DTO列表则遇到问题。

这是我的DTO(已编辑):

public class DirectoryDTO {
    String id;
    String personFirstName;
    String personLastName;
    String building;


public DirectoryDTO(String id, String personFirstName, String personLastName, String building) {
    this.id = id;
    this.personFirstName = personFirstName;
    this.personLastName = personLastName;
    this.building= building;
}


public DirectoryDTO() {

}
    //Getters and setter
}

我的控制器:

public List<DirectoryDTO> getTestDTO(){
    ModelMapper modelMapper = new ModelMapper();
    List<DirectoryDTO> directoryDTO = ObjectMapperUtils.
        mapAll(directoryService.getDirectory("DD"), DirectoryDTO.class);

    return directoryDTO;
}

ObjectMapperUtils类:

public class ObjectMapperUtils {
  public static <D, T> List<D> mapAll(final Collection<T> entityList, Class<D> outClass) {
    return entityList
            .stream()
            .map(entity -> map(entity, outClass))
            .collect(Collectors.toList());
  }
}

返回的DTO:

[
    {
        "id": null,
        "personFirstName": null,
        "personLastName": null,
        "building": null
    },
    {
        "id": null,
        "personFirstName": null,
        "personLastName": null,
        "building": null
    },
....
]

DTO具有正确的行数,但显然数据未写入对象。

完全披露我从某处复制了mapAll()函数,我不确定它是否按预期工作。

编辑:

在对它进行了多次黑客攻击后,我注意到当我尝试从HQL查询中写入我的DTO时,它拒绝了。所以让我发布更多代码。

查询:

query = em.createQuery(
        "select new dto.DirectoryDTO(p.id, p.firstName, p.lastName, p.hrper)  " +
                "  from Person p " +
                "join p.hrp hrp " +
                "left join p.pst ps " +
                "join pos.depts dept " +
                "where (trunc(:sysdate) between ps.StartDate AND ps.EndDate" +
                " OR (ps.StartDate <= trunc(:sysdate) AND ps.EndDate IS NULL)) " +
                "AND dept.deptsId = :department")
.setParameter("sysdate", getSysdate())
.setParameter("department", department));

应为这些实体正确设置所有连接

0 个答案:

没有答案