java 如何使Model Mapper正确地从实体Map到DTO

wqsoz72f  于 2022-12-28  发布在  Java
关注(0)|答案(1)|浏览(180)

作为上下文,我创建了一个 Boot ,然后遇到了下一个问题,当我将Entity类Map到DTO时,它不会接受其中一个字段,更准确地说是department字段。

public ItemDTO updateItem(Long departmentId, Long itemId, ItemDTO itemDTO) throws ApiException {
        Department department = departmentRepository.findById(departmentId).orElseThrow(
                () -> new ApiException("Department with this id does not exist ",
                        HttpStatus.NOT_FOUND));

        Item foundItem = validateItem(itemId);
        Item convertedItem = mapper.convertToType(itemDTO, Item.class);
        if (convertedItem.getStock() < 0) {
            throw new ApiException("Stock must be a positive value", HttpStatus.BAD_REQUEST);
        }

        if (convertedItem.getStockThreshold() < 0) {
            throw new ApiException("Stock threshold must be a positive value", HttpStatus.BAD_REQUEST);
        }

        itemDTO.setId(itemId);
        itemDTO.setDepartment(mapper.convertToType(department, DepartmentDTO.class));
        foundItem = mapper.convertToType(itemDTO, Item.class);
        itemRepository.save(foundItem);

//        ItemDTO returnItem = mapper.convertToType(convertedItem, ItemDTO.class);
        logger.info("Updated item");
        return itemDTO;
    }

这里是转换前的x1c 0d1x
转换后

编辑!
这是我的Mapper类

@Component
public class Mapper {
    private final ModelMapper modelMapper;
    private final Logger logger = LoggerFactory.getLogger(ModelMapper.class);

    public Mapper(ModelMapper modelMapper) {
        this.modelMapper = modelMapper;
    }

    public <T> T convertToType(Object source, Class<T> resultClass) {
        logger.debug("converted object from " + source.getClass().getSimpleName() + " to " + resultClass.getSimpleName());
        return modelMapper.map(source, resultClass);
    }
}

项目DTO类

@AllArgsConstructor

@NoArgsConstructor
@Setter
public class ItemDTO {
    private Long id;
    private String description;
    private String price;
    private int stock;

    private int stockThreshold;

    private DepartmentDTO department;

    public Long getId() {
        return id;
    }

    public String getDescription() {
        return description;
    }

    public String getPrice() {
        return price;
    }

    public int getStock() {
        return stock;
    }

    public int getStockThreshold() {
        return stockThreshold;
    }

    public Long getDepartment() {
        return department.getId();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ItemDTO itemDTO = (ItemDTO) o;
        return stock == itemDTO.stock && stockThreshold == itemDTO.stockThreshold &&
                id.equals(itemDTO.id) && description.equals(itemDTO.description) &&
                price.equals(itemDTO.price) && department.equals(itemDTO.department);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, description, price, stock);
    }

和项目类

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "ITEMS")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Long id;
    private String description;
    private String price;
    private int stock;

    private int stockThreshold = 5;
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "department_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private Department department;

    @Override
    public String toString() {
        return "Item{" +
                "id=" + id +
                ", description='" + description + '\'' +
                ", price='" + price + '\'' +
                ", stock=" + stock +
                ", department=" + department +
                '}';
    }
}

部门DTO类别:

@NoArgsConstructor

@Getter
@Setter
public class DepartmentDTO {
    private Long id;
    private String description;
    private List<Item> items;

    public DepartmentDTO(long id, String description) {
        this.id = id;
        this.description = description;
    }

    @Override
    public String toString() {
        return "DepartmentDTO{" +
                "id=" + id +
                ", description='" + description + '\'' +
                ", items=" + items +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        DepartmentDTO that = (DepartmentDTO) o;
        return Objects.equals(id, that.id) && Objects.equals(description, that.description) && Objects.equals(items, that.items);
    }

//    @Override
//    public int hashCode() {
//        return Objects.hash(id, description, items);
//    }
}

部门分类

@NoArgsConstructor
@Entity
@Getter
@Setter
@Table(name = "DEPARTMENTS")
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String description;
    @OneToMany(mappedBy = "department", fetch = FetchType.EAGER,
            cascade = CascadeType.ALL)
    private List<Item> items;
    public Department(Long id, String description) {
        this.id = id;
        this.description = description;
    }

    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", description='" + description + '\'' +
                ", items=" + items +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Department)) return false;
        Department that = (Department) o;
        return id.equals(that.id) && Objects.equals(description, that.description) && Objects.equals(items, that.items);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, description, items);
    }

}

最小可重复示例:

Department department = new Department(1L, "first");
ItemDTO  itemDTO = new ItemDTO(1L, "modified description for update",
                "200$", 200, 6, mapper.convertToType(department, 
DepartmentDTO.class));
Item item = mapper.convertToType(itemDTO,Item.class);

item的department字段将为空,因为我的Map器在Mapdepartment时出现问题。

56lgkhnf

56lgkhnf1#

***前言:***感谢您对我的评论的快速回应。我看到您对Stack Overflow相当陌生,回顾您的问题,我注意到一个趋势。我建议您阅读How do I ask a good question?Minimal, Reproducible Example
答复:

TLDR:您必须使ItemDTO#getDepartment返回department对象。
我是这样处理这个问题的:
1.创建了一个新项目来保存和运行您的代码。
1.清理了你的代码。

  • 删除了JPA注解。
  • 删除Jackson注解。
  • 删除Lombok注解。

1.我唯一无法解析的依赖项是ModelMapper。我假设这是来自ModelMapper。我以前从未使用过它,但我假设它像Jackson这样的流行序列化库一样使用getter/setter。
1.这让我检查了getter/setter,发现ItemDTO#getDepartment返回的是部门的ID,而不是DepartmentDTO对象本身。
我想我会分享我是如何处理你的问题的,希望它能帮助你更好地自己解决问题!

相关问题