目录
将一个对象的值赋值给另一个对象时(属性名相同),就需要转换类了.
- package com.sinosoft.springbootplus.office.convert;
-
- import com.sinosoft.springbootplus.office.domain.entity.JgjgOffice;
- import com.sinosoft.springbootplus.office.vo.JgjgOfficeQueryVo;
- import org.mapstruct.Mapper;
- import org.mapstruct.factory.Mappers;
-
- /**
- *类型转换器
- * @author ljk
- */
- @Mapper
- public interface JgjgOfficeConvert {
- JgjgOfficeConvert INSTANCE = Mappers.getMapper(JgjgOfficeConvert.class);
-
- /**
- * entity->vo
- * @param jgjgOffice
- * @return
- */
- JgjgOfficeQueryVo jgjgOfficeToJgjgOfficeQueryVo(JgjgOffice jgjgOffice);
- }
3.具体使用
- public JgjgOfficeQueryVo getJgjgOfficeById(Long id){
- JgjgOffice jgjgOfficeById = jgjgOfficeDomain.getJgjgOfficeById(id);
- JgjgOfficeQueryVo jgjgOfficeQueryVo = JgjgOfficeConvert.INSTANCE.jgjgOfficeToJgjgOfficeQueryVo(jgjgOfficeById);
- return jgjgOfficeQueryVo;
- }
例如:
- @Data
- @Accessors(chain = true)
- @EqualsAndHashCode(callSuper = true)
- @ApiModel(value = "JgjgNoticeReceive对象", description = "监管机构系统-收发文-收件人")
- public class JgjgNoticeReceive extends BaseEntity {
-
- private static final long serialVersionUID = 1L;
-
-
- @ApiModelProperty(value = "主键", required = true)
- @TableId(value = "id", type = IdType.ID_WORKER)
- private Long id;
-
- @ApiModelProperty(value = "收件人ID")
- private Long receiveId;
-
- @ApiModelProperty(value = "收件人姓名")
- private String receiveName;
-
- }
- @Data
- @Accessors(chain = true)
- @EqualsAndHashCode(callSuper = true)
- @ApiModel(value = "JgjgPerson对象", description = "监管机构系统-人员管理")
- public class JgjgPerson extends BaseEntity {
-
- private static final long serialVersionUID = 1L;
-
- @ApiModelProperty(value = "主键", required = true)
- @TableId(value = "id", type = IdType.ID_WORKER)
- private Long id;
-
- @ApiModelProperty(value = "姓名")
- private String name;
-
- @ApiModelProperty(value = "用户ID")
- private Long userId;
-
- }
向以上两种类: name 对应 receiveName, userId对应receiveId , 并且id 忽略.将如何转换呢?
- @Mappings({
- @Mapping(source = "name", target = "receiveName"),
- @Mapping(source = "userId", target = "receiveId"),
- @Mapping(target = "id", ignore = true)
- })
- JgjgNoticeReceive jgjgPerson2JgjgNoticeReceive(JgjgPerson jgjgPerson);
source里面填写的是要转换的属性名,,target里面填的的是被转换后的属性名.ignore指的是忽略,id不做转换.
以上@Mappings注解和@Mapping注解则可以完成类里面不同属性名之间的相互转换.