MapStruct使用技巧
在设计数据库时,往往会增加一个字段features varchar(1000),用来做扩展字段,避免改表结构的。尤其是针对给某一条记录进行”打标操作“。
那么,在DO类转为域模型对象时就有一个转换问题。
下面介绍使用mapstruct优雅的进行转换
package com.chinaunicom.base.server.converter; import com.chinaunicom.base.domain.model.userspace.UserSpace; import com.chinaunicom.base.server.converter.worker.UserSpaceConvert; import com.chinaunicom.base.server.dao.datamodel.UserSpaceEntity; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Mappings; import org.mapstruct.factory.Mappers; import java.util.List; @Mapper(componentModel = "spring", uses = {UserSpaceConvert.class}) public interface UserSpaceBaseConverter { UserSpaceBaseConverter INSTANCES = Mappers.getMapper(UserSpaceBaseConverter.class); @Mappings({ @Mapping(source = "id", target = "id"), @Mapping(source = "employeeName", target = "employeeName"), @Mapping(source = "rootSpace", target = "rootSpace"), @Mapping(source = "createTime", target = "createTime"), @Mapping(source = "deleted", target = "deleted") }) UserSpaceEntity to(UserSpace userSpace); @Mappings({ @Mapping(source = "id", target = "id"), @Mapping(source = "employeeName", target = "employeeName"), @Mapping(source = "rootSpace", target = "rootSpace"), @Mapping(source = "createTime", target = "createTime"), @Mapping(source = "deleted", target = "deleted"), @Mapping(target = "age", expression = "java(com.chinaunicom.base.server.converter.worker.UserSpaceConvert.getAgeFromFeatures(userSpaceEntity.getFeatures()))") }) UserSpace back(UserSpaceEntity userSpaceEntity); List<UserSpaceEntity> toList(List<UserSpace> source); List<UserSpace> backList(List<UserSpaceEntity> source); }
UserSpaceEntity
public class UserSpaceEntity { private Integer id; private String employeeName; private String rootSpace; private Date createTime; private Integer deleted;//1 删除 0 未删除 private String features; }
UserSpace
public class UserSpace implements Serializable { private Integer id; private String employeeName; private String rootSpace; private Date createTime; private Integer deleted = 0; private Integer age; }
其中 UserSpaceEntity 的features是保存的JSON格式数据,数据库中也是JSON
public class UserSpaceConvert { public static Integer getAgeFromFeatures(String json) { Map<String,Object> valueMap = JSON.parseObject(json, Map.class); if (valueMap.containsKey("age")) { return Integer.valueOf(valueMap.get("age").toString()); } return null; } }