Java ModelMapper - Уплощение сущности в массив целых чисел - PullRequest
0 голосов
/ 30 мая 2018

Я пытаюсь использовать превосходную библиотеку Java ModelMapper, чтобы свести мои сущности JPA к DTO.Одним из объектов является «ResourceItem», который имеет отношение «многие ко многим» с объектом «ResourceCategory».

    @Entity
public class ResourceItem {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int ID;

    @ManyToMany(mappedBy = "resources")
    private List<ResourceCategory> resourceCategories = new ArrayList<>();

    @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
    @JoinTable(name = "TagsResources")
    private List<Tag> tags = new ArrayList<>();

    @OneToOne
    @JoinColumn(name = "FileID")
    private FileResource file;

    @Column(name = "Name")
    private String name;

    public ResourceItem() {

    } }

и

@Entity
public class ResourceCategory {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int ID;

    @Column(name = "Title")
    private String title;

    @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
    private List<ResourceItem> resources = new ArrayList<>();

    public ResourceCategory() {

    }

Я пытаюсь сгладить ResourceItemтак что вместо того, чтобы содержать ArrayList из ResouceCategories, вместо этого у него есть ArrayList из Integer, который просто ссылается на значения идентификаторов связанных ResouceCategories.

public class ResourceItemDTO {
private int ID;
private List<Integer> resourceCategoriesID = new ArrayList<>();
private List<TagDTO> tags = new ArrayList<>();
private String filePath;
private String name;}

Я проверяю его следующим образом:

@Test
public void testResourceItems() {
    List<ResourceCategory> cList = new ArrayList<>();
    List<ResourceItem> iList = new ArrayList<>();
    List<Tag> tList = new ArrayList<>();
    tList.add(new Tag(1, "Tag1"));
    tList.add(new Tag(2, "Tag2"));
    ResourceCategory cat = new ResourceCategory();
    ResourceItem itm1 = new ResourceItem(1, tList, new FileResource(1, "Path", "Caption"), "Name");
    ResourceItem itm2 = new ResourceItem(1, tList, new FileResource(2, "Path2", "Caption2"), "Name2");
    iList.add(itm1);
    iList.add(itm2);
    cat.setID(1);
    cat.setResources(iList);
    cList.add(cat);
    itm1.setResourceCategories(cList);
    itm2.setResourceCategories(cList);

    for (ResourceItem itm : iList) {
        assertThat(mapper.map(itm, ResourceItemDTO.class).getFilePath()).isEqualTo(itm.getFile().getPath());
        assertThat(mapper.map(itm, ResourceItemDTO.class).getResourceCategoriesID())
                .contains(itm.getResourceCategories().get(0).getID());
    }

    assertThat(mapper.map(cat, ResourceCategoryDTO.class).getResources().size())
            .isEqualTo(cat.getResources().size());
    assertThat(mapper.map(cat, ResourceCategoryDTO.class).getResources().get(0).getFilePath())
            .isEqualTo(cat.getResources().get(0).getFile().getPath());

}
    @Column(name = "Title")
    private String title;

    @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
    private List<ResourceItem> resources = new ArrayList<>() ;}

ModelMapper не смог автоматически сгладить ArrayList из ResourceCategories в ArrayList of Integers.Я попытался создать собственное сопоставление следующим образом:

    @Bean
public ModelMapper modelMapper() {
    ModelMapper mapper = new ModelMapper();
    PropertyMap<ResourceItem, ResourceItemDTO> rItemMap = new PropertyMap<ResourceItem, ResourceItemDTO>() {

        @Override
        protected void configure() {
            map().setResourceCategoriesID(source.getResourceCategories().stream().map(e -> {
                return e.getID();
            }).collect(Collectors.toList()));

        }
    };

    mapper.addMappings(rItemMap);
    return mapper;
}

Однако я получаю ошибку Failed to configure mappings, основной причиной которой является NullPointerException.Видимо, я подошел к задаче неправильно.Как правильно выполнить такое выравнивание?

Заранее спасибо.

1 Ответ

0 голосов
/ 27 июня 2018

Вы можете попробовать конвертер, чтобы отобразить ResourceCategories в список целых чисел.

mapper.addMappings(new PropertyMap<ResourceItem, ResourceItemDTO>() {
    @Override
    protected void configure() {
        using(ctx -> ctx.getSource().stream().map(ResourceCategory::getID).collect(Collectors.toList())
            .map().setResourceCategoriesID(source.getResourceCategories());
    }
}
...