自定义转换类型
expression="java(。。。)"
1、doTrim函数,toJsonString函数、自定义java函数(工具类见附录)
import com.dm.bs.model.vo.BsFieldTransResult;
import com.dm.bs.model.vo.BsFieldTransVO;
import com.dm.bs.repository.entity.BsFieldTrans;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
/**
* BsFieldTrans转换器
*/
@Mapper(uses = {TypeConversionWorker.class})
public interface BsFieldTransMapping {
BsFieldTransMapping INSTANCE = Mappers.getMapper(BsFieldTransMapping.class);
@Mapping(target = "targetUrl",source = "targetUrl",qualifiedByName = "doTrim")
@Mapping(target = "transKey",source = "transKey",qualifiedByName = "toJsonString")
@Mapping(target = "transVal",source = "transVal",qualifiedByName = "toJsonString")
@Mapping(target = "relatedField", expression = "java(typeConversionWorker.generateRelatedField(bsFieldTransVO.getTransKey(), bsFieldTransVO.getTransVal()))") //使用工具类处理
BsFieldTrans transToBsFieldTrans(BsFieldTransVO bsFieldTransVO);
@Mapping(target = "relatedField",source = "relatedField",qualifiedByName = "listStr2CommaStr")
BsFieldTransResult transToBsFieldTransResult(BsFieldTrans bsFieldTrans);
}
2、
附录:
1、转换工具类
import com.dm.bs.model.vo.TransKeyVO;
import com.dm.bs.model.vo.TransValVO;
import com.dm.bs.util.JacksonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.mapstruct.Named;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Mapping通用转换
*/
@Component
@Named("TypeConversionWorker")
public class TypeConversionWorker {
/**
* 对象转json字符串
*
* @param obj
* @return
*/
@Named("toJsonString")
public String toJsonString(Object obj) {
if (Objects.isNull(obj)) {
return null;
}
return JacksonUtil.toJsonString(obj);
}
/**
* 去空格
*
* @param str
* @return
*/
@Named("doTrim")
public String doTrim(String str) {
if (StringUtils.isEmpty(str)) {
return null;
}
return str.trim();
}
/**
* 字符串转List对象
*
* @param str
* @return
*/
@Named("toStrList")
public List toStrList(String str) {
if (StringUtils.isEmpty(str)) {
return null;
}
return JacksonUtil.jsonToObjByTypeRf(str, new TypeReference>() {
});
}
/**
* json字符串转换为Map
*
* @param obj
* @return
*/
@Named("toStrObjMap")
public Object toStrObjMap(Object obj) {
if (Objects.isNull(obj)) {
return null;
}
return JacksonUtil.jsonToObjByTypeRf(obj.toString(), new TypeReference
2、工具类
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class JacksonUtil {
private static ObjectMapper mapper = new ObjectMapper();
/**
* 对象转json
*
* @param object
* @return
*/
public static String toJsonString(Object object) {
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
log.error("...Err...Jackson转换字符串(String)过程失败:::", e);
e.printStackTrace();
}
return null;
}
/**
* json转对象
*
* @param json
* @param clazz
* @param
* @return
*/
public static T jsonToBean(String json, Class clazz) {
try {
return mapper.readValue(json, clazz);
} catch (JsonProcessingException e) {
log.error("...Err...Jackson转换对象(Object)过程失败:::", e);
e.printStackTrace();
}
return null;
}
/**
* 字符串转换为List
*
* @param listStr
* @param typeReference new TypeReference>() {}
* @param
* @return
*/
public static T jsonToObjByTypeRf(String listStr, TypeReference typeReference) {
try {
return mapper.readValue(listStr, typeReference);
} catch (JsonProcessingException e) {
log.error("...Err...Jackson转换Object过程失败:::", e);
e.printStackTrace();
}
return null;
}
}
是不是有时候发现明明source和target不是同一个类型,但是却转换成功了,这是因为mapstruct有一套自己的类型转换机制
自动转换
以下的类型之间是mapstruct自动进行类型转换的。
@Data
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@AllArgsConstructor
public class Item1 {
Long itemId;
String title;
}
@Data
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@AllArgsConstructor
public class Item2 {
Long itemId;
String title;
}
@Data
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@AllArgsConstructor
public class Sku2 {
Long skuId;
String skuCode;
String skuPrice;
List nameList;
Item1 item;
}
@Data
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@AllArgsConstructor
public class SkuDTO2 {
Long skuId;
String skuCode;
Long skuPrice;
List nameList;
Item2 item;
}
@Mapper
public interface ItemConvert {
ItemConvert INSTANCE = Mappers.getMapper(ItemConvert.class);
SkuDTO2 domain2Dto(Sku2 sku2);
}
// 以下为mapstruct自动生成
public class ItemConvertImpl implements ItemConvert {
@Override
public SkuDTO2 domain2Dto(Sku2 sku2) {
if ( sku2 == null ) {
return null;
}
SkuDTO2 skuDTO2 = new SkuDTO2();
skuDTO2.setSkuId( sku2.getSkuId() );
skuDTO2.setSkuCode( sku2.getSkuCode() );
if ( sku2.getSkuPrice() != null ) {
skuDTO2.setSkuPrice( Long.parseLong( sku2.getSkuPrice() ) );
}
List list = sku2.getNameList();
if ( list != null ) {
skuDTO2.setNameList( new ArrayList( list ) );
}
skuDTO2.setItem( item1ToItem2( sku2.getItem() ) );
return skuDTO2;
}
protected Item2 item1ToItem2(Item1 item1) {
if ( item1 == null ) {
return null;
}
Item2 item2 = new Item2();
item2.setItemId( item1.getItemId() );
item2.setTitle( item1.getTitle() );
return item2;
}
自定义转换类型
expression="java(。。。)"
@Mapper(imports={DemandSourceEnum.class})
public interface CarDealMapper {
CarDealMapper INSTANCE = Mappers.getMapper(CarDealMapper.class);
@Mappings({
@Mapping(target = "demandSource", expression = "java(DemandSourceEnum.getMeaning(carDealDO.getDemandSource()))"),
SaleDemandVO doToVo(CarDealDO carDealDO);
}
@Mapper
public interface ItemConvert {
ItemConvert INSTANCE = Mappers.getMapper(ItemConvert.class);
SkuDTO2 domain2Dto(Sku2 sku2);
default Item2 item1ToItem2(Item1 item1) {
if (item1 == null) {
return null;
}
Item2 item2 = new Item2();
item2.setItemId(11111L);
item2.setTitle(item1.getTitle());
return item2;
}
}
// mapstruct 的实现类
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2019-07-30T18:38:11+0800",
comments = "version: 1.3.0.Final, compiler: javac, environment: Java 1.8.0_101 (Oracle Corporation)"
)
public class ItemConvertImpl implements ItemConvert {
@Override
public SkuDTO2 domain2Dto(Sku2 sku2) {
if ( sku2 == null ) {
return null;
}
SkuDTO2 skuDTO2 = new SkuDTO2();
skuDTO2.setSkuId( sku2.getSkuId() );
skuDTO2.setSkuCode( sku2.getSkuCode() );
if ( sku2.getSkuPrice() != null ) {
skuDTO2.setSkuPrice( Long.parseLong( sku2.getSkuPrice() ) );
}
List list = sku2.getNameList();
if ( list != null ) {
skuDTO2.setNameList( new ArrayList( list ) );
}
// mapstruct直接调用的是在接口中自定义的实现
skuDTO2.setItem( item1ToItem2( sku2.getItem() ) );
return skuDTO2;
}
}
public class BooleanStrategy {
public String booleanToString(Boolean value) {
if (value == null) {
return "--";
}
return value ? "是" : "否";
}
public Integer booleanToInteger(Boolean value) {
if (value == null) {
return null;
}
return value ? 1 : 0;
}
public Boolean IntegerToBoolean(Integer value) {
if (value == null) {
return null;
}
return value == 0 ? false : true;
}
public String dateFormate(Date date) {
if (date == null) {
return "--";
}
return DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
}
}
@Mapper(uses = BooleanStrategy.class)
public interface CarDealMapper {
CarDealMapper INSTANCE = Mappers.getMapper(CarDealMapper.class);
CarDealDO dtoToDo(PlateCityMessageDTO plateCityMessageDTO);
}
方法中target和source 类型满足 BooleanStrategy方法的,会自动进行调用这个方法的类型转换进行处理
若是我们需要给一些属性定义一个固定的值,这个时候可以使用 constant
@Mapping(target = "whetherPass", constant = "true")
CentralizedNewCarShipDTO doToDubboDto(CarDealDO carDealDO);
@Mapping(target = "createTime", dateFormat = "yyyy-MM-dd HH:mm:ss", expression = "java(new Date())")
CarDTO doToDTO(CarDO carDO);
另外还有numberFormat
定义数字的格式转换
defaultValue
/**
* 单个参数的直接使用
*
* @param carDO source do
* @return target dto
*/
@Mapping(target = "userName", constant = "yby")
@Mapping(target = "modelColor", source = "modelColor", defaultValue = "标致")
@Mapping(target = "createTime", dateFormat = "yyyy-MM-dd HH:mm:ss", expression = "java(new Date())")
CarDTO doToDTO(CarDO carDO);
额外的请参考 org.mapstruct.Mapping
Collection转换
原理是遍历source collection然后转换类型,put到target collection中 如果是可以自动转换的则自动转换,同date type conversion;若是无法自动转换的,则会查看是否有可以调用的类型
@Mapper(imports = Date.class)
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
/**
* 基本类型collection的转换
*
* @param integers
* @return
*/
Set integerSetToStringSet(Set integers);
/**
* 调用存在已有方法的转换
*
* @param cars
* @return
*/
List carsToCarDtos(List cars);
/**
* 单个参数的直接使用
*
* @param carDO source do
* @return target dto
*/
@Mapping(target = "userName", constant = "yby")
@Mapping(target = "modelColor", source = "modelColor", defaultValue = "标致")
@Mapping(target = "createTime", dateFormat = "yyyy-MM-dd HH:mm:ss", expression = "java(new Date())")
CarDTO doToDTO(CarDO carDO);
/**
* DTO转为VO
*
* @param warehouseValidDTOList
* @return
*/
List dtoToVo(List warehouseValidDTOList);
}
// mapstruct实现
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2019-07-30T19:27:05+0800",
comments = "version: 1.3.0.Final, compiler: javac, environment: Java 1.8.0_101 (Oracle Corporation)"
)
public class CarMapperImpl implements CarMapper {
@Override
public Set integerSetToStringSet(Set integers) {
if ( integers == null ) {
return null;
}
Set set = new HashSet( Math.max( (int) ( integers.size() / .75f ) + 1, 16 ) );
for ( Integer integer : integers ) {
set.add( String.valueOf( integer ) );
}
return set;
}
@Override
public List carsToCarDtos(List cars) {
if ( cars == null ) {
return null;
}
List list = new ArrayList( cars.size() );
for ( CarDO carDO : cars ) {
list.add( doToDTO( carDO ) );
}
return list;
}
@Override
public CarDTO doToDTO(CarDO carDO) {
if ( carDO == null ) {
return null;
}
CarDTO carDTO = new CarDTO();
if ( carDO.getModelColor() != null ) {
carDTO.setModelColor( carDO.getModelColor() );
}
else {
carDTO.setModelColor( "标致" );
}
if ( carDO.getNewCarGuidePrice() != null ) {
carDTO.setNewCarGuidePrice( BigDecimal.valueOf( carDO.getNewCarGuidePrice() ) );
}
carDTO.setBrandCode( carDO.getBrandCode() );
carDTO.setBrandName( carDO.getBrandName() );
carDTO.setSeriesCode( carDO.getSeriesCode() );
carDTO.setSeriesName( carDO.getSeriesName() );
carDTO.setModelCode( carDO.getModelCode() );
carDTO.setModelName( carDO.getModelName() );
carDTO.setModelColorCode( carDO.getModelColorCode() );
carDTO.setUserName( "yby" );
carDTO.setCreateTime( new Date() );
return carDTO;
}
@Override
public List dtoToVo(List warehouseValidDTOList) {
if ( warehouseValidDTOList == null ) {
return null;
}
List list = new ArrayList( warehouseValidDTOList.size() );
for ( WarehouseValidDTO warehouseValidDTO : warehouseValidDTOList ) {
list.add( warehouseValidDTOToWarehouseValidPageVO( warehouseValidDTO ) );
}
return list;
}
protected WarehouseValidPageVO warehouseValidDTOToWarehouseValidPageVO(WarehouseValidDTO warehouseValidDTO) {
if ( warehouseValidDTO == null ) {
return null;
}
WarehouseValidPageVO warehouseValidPageVO = new WarehouseValidPageVO();
warehouseValidPageVO.setId( warehouseValidDTO.getId() );
warehouseValidPageVO.setWarehouseNo( warehouseValidDTO.getWarehouseNo() );
warehouseValidPageVO.setWarehouseName( warehouseValidDTO.getWarehouseName() );
warehouseValidPageVO.setPlateValid( warehouseValidDTO.getPlateValid() );
return warehouseValidPageVO;
}
}
map
public interface SourceTargetMapper {
@MapMapping(valueDateFormat = "dd.MM.yyyy")
Map longDateMapToStringStringMap(Map source);
}
// mapstruct自己实现
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2019-07-30T19:35:22+0800",
comments = "version: 1.3.0.Final, compiler: javac, environment: Java 1.8.0_101 (Oracle Corporation)"
)
public class SourceTargetMapperImpl implements SourceTargetMapper {
@Override
public Map longDateMapToStringStringMap(Map source) {
if ( source == null ) {
return null;
}
Map map = new HashMap( Math.max( (int) ( source.size() / .75f ) + 1, 16 ) );
for ( java.util.Map.Entry entry : source.entrySet() ) {
String key = new DecimalFormat( "" ).format( entry.getKey() );
String value = new SimpleDateFormat( "dd.MM.yyyy" ).format( entry.getValue() );
map.put( key, value );
}
return map;
}
}