MapStruct枚举类处理
Posted 波子汽水yeah
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MapStruct枚举类处理相关的知识,希望对你有一定的参考价值。
MapStruct对枚举类的处理 记录一下
比如有个性别枚举
public enum GenderEnum
Male("1", "男"),
Female("0", "女");
private String code;
private String name;
public String getCode()
return this.code;
public String getName()
return this.name;
GenderEnum(String code, String name)
this.code = code;
this.name = name;
GenderEnum()
GenderEnum getByNmae(String name)
for (GenderEnum ge: GenderEnum.values())
if (ge.name.equals(name))
return ge;
return null;
在A类中 是这个枚举 private GenderEnum gender;
在B类中是字符串的 男 女 sex字段 private String sex;
B转换成A的时候这个对应关系是这样的
package com.mb.sleep.test.vodtotest.po;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@Mapper
public interface StudentVomapper
StudentVomapper INSTANCE = Mappers.getMapper(StudentVomapper.class);
@Mappings(
@Mapping(source = "sex", target = "gender"),
@Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
)
Student studentVo2Student(StudentVO studentVO);
//枚举类字段转换
default GenderEnum customConveter(String name)
for (GenderEnum ge: GenderEnum.values())
if (ge.getName().equals(name))
return ge;
return null;
编译后自动生成的代码如下:注意这段代码是自动生成的不是手写的
public class StudentVomapperImpl implements StudentVomapper
@Override
public Student studentVo2Student(StudentVO studentVO)
if ( studentVO == null )
return null;
Student student = new Student();
student.setGender( customConveter( studentVO.getSex() ) ); // 转换枚举类
try
if ( studentVO.getBirthday() != null )
student.setBirthday( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).parse( studentVO.getBirthday() ) );
catch ( ParseException e )
throw new RuntimeException( e );
student.setName( studentVO.getName() );
student.setAge( studentVO.getAge() );
student.setHeight( studentVO.getHeight() );
return student;
mapping中的customConveter 方法负责转换
A转成B时这样写
@Mappings(
@Mapping(source = "gender.name", target = "sex"),
@Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
)
StudentVO student2StudentVO(Student student);
以上是关于MapStruct枚举类处理的主要内容,如果未能解决你的问题,请参考以下文章