Spring 问题映射字段ModelMapper
我使用DTO和modelMapper是为了不让某些字段可见。 我有一个类别实体,可以有子类别Spring 问题映射字段ModelMapper,spring,modelmapper,Spring,Modelmapper,我使用DTO和modelMapper是为了不让某些字段可见。 我有一个类别实体,可以有子类别 public class CategoryEntity { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Long id; @Column(length = 30, nullable = false) private String categoryKeyId; @Colu
public class CategoryEntity {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
@Column(length = 30, nullable = false)
private String categoryKeyId;
@Column(nullable = false)
private String name;
@ManyToOne(optional = true, fetch = FetchType.LAZY)
@JoinColumn(name="parent_id", nullable=true)
private CategoryEntity parentCategory;
// allow to delete also subcategories
@OneToMany(mappedBy="parentCategory", cascade = CascadeType.ALL)
private List<CategoryEntity> subCategories;
}
在此模型中,我希望parentCategoryKeyId与父对象的categoryKeyId匹配
例如,如果我创建了一个“顶级”类别:
{
"name": "topCategory"
}
它返回给我:
{
"categoryKeyId": "jUcpO27Ch2YrT2zkLr488Q435F8AKS",
"name": "topCategory",
"subCategories": null
}
当我这样做时:
{
"name": "sub",
"parentCategoryKeyId": "jUcpO27Ch2YrT2zkLr488Q435F8AKS"
}
在控制器中,我将rest对象传递给DTO层,该层调用服务:
public CategoryRestResponseModel createCategory(@RequestBody CategoryRequestModel categoryRequestModel) {
CategoryRestResponseModel returnValue = new CategoryRestResponseModel();
if( categoryRequestModel.getName().isEmpty())
throw new NullPointerException(ErrorMessages.MISSING_REQUIRED_FIELDS.getErrorMessage());
ModelMapper modelMapper = new ModelMapper();
CategoryDto categoryDto = modelMapper.map(categoryRequestModel, CategoryDto.class);
CategoryDto createdCategory = categoryService.createCategory(categoryDto);
returnValue = modelMapper.map(createdCategory, CategoryRestResponseModel.class);
return returnValue;
}
我的类别是基本的POJO:
@Getter @Setter
public class CategoryDto implements Serializable {
@Getter(AccessLevel.NONE)
private static final long serialVersionUID = 1L;
private String categoryKeyId;
private String parentCategoryKeyId;
private String name;
private CategoryDto parentCategory;
private List<CategoryDto> subCategories;
}
我的问题是我想保存子类别并检索与categoryKeyId匹配的ID
在数据库中,我的条目应该是这样的
我的第一份参赛作品应包括:
id=1-父项id=null,类别密钥id=jUcpO27Ch2YrT2zkLr488Q435F8AKS,名称=topCategory。。。
以及:
id=2-父项\u id=1,类别\u密钥\u id=“另一个生成的密钥”,名称=子项
不幸的是,我只是保留了id、categorykeyid和名称。
我从CategoryDto中删除了id,并获得:1)Converter org.modelmapper.internal.Converter。NumberConverter@348fc3d8无法将java.lang.String转换为java.lang.Long。我用“肮脏”的方式解决了这个问题。
我只是更改了条目中的对象并添加了一个长id
它给了我:
@Getter @Setter
public class CategoryRequestModel {
private Long id;
private String name;
private String parentCategoryKeyId;
}
我用一种“肮脏”的方式解决了它。
我只是更改了条目中的对象并添加了一个长id
它给了我:
@Getter @Setter
public class CategoryRequestModel {
private Long id;
private String name;
private String parentCategoryKeyId;
}
@Getter @Setter
public class CategoryRequestModel {
private Long id;
private String name;
private String parentCategoryKeyId;
}