Form类里面有Enum类,po存到数据库时,想存枚举类的code,需要将Enum转换为String(code)
src class
, Form
@Data
public class BaseInfoForm implements Serializable {
private static final long serialVersionUID = 2261054116525535919L;
private String contractName;
private ContractTypeEnum contractType;
}
target class
, po
public class TbContManBasic extends Model {
private static final long serialVersionUID = 1L;
private String contractName;
private String contractType;
ContractTypeEnum class
, Enum
@Getter
public enum ContractTypeEnum {
FRAMEWORK_AGREEMENT("FRAMEWORK_AGREEMENT", "框架协议"),
FORMAL_CONTRACT("FORMAL_CONTRACT", "正式合同"),
INVESTMENT_COOPERATION_AGREEMENT("INVESTMENT_COOPERATION_AGREEMENT", "投资合作协议"),
SUPPLEMENTAL_AGREEMENT("SUPPLEMENTAL_AGREEMENT", "补充协议"),
TERMINATION_AGREEMENT("TERMINATION_AGREEMENT", "终止协议"),
BIG_ISSUES("BIG_ISSUES", "重大事项"),
INTENTION_AGREEMENT("INTENTION_AGREEMENT", "意向协议"),
GOVERNMENT_COOPERATION_AGREEMENT("GOVERNMENT_COOPERATION_AGREEMENT", "政府合作协议"),
OTHER_CONT("OTHER_CONT", "其他")
;
ContractTypeEnum(String code, String message) {
this.code = code;
this.message = message;
}
private String code;
private String message;
/**
* 重写toString()返回code
* @return
*/
@Override
public String toString() {
return this.code;
}
}
要重写枚举类的
toString()
方法用来获取code,因为Enum类只有一个toString()
方法可以重写
commons-beanutils
commons-beanutils
1.9.3
import org.apache.commons.beanutils.Converter;
public class Enum2StringConverter2 implements Converter{
@Override
public String convert(Class aClass, Object o) {
try {
return ((Enum) o).toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
//当有ContractTypeEnum这个类时,使用转换器转换ContractTypeEnum这个枚举类,转换为String,不影响其他类型转换
ConvertUtils.register(new Enum2StringConverter2(), ContractTypeEnum.class);
//tbContManBasic是target, manContractForm.getBaseInfoForm()是src
BeanUtils.copyProperties(tbContManBasic, manContractForm.getBaseInfoForm());
public class Enum2StringConverter implements Converter {
@Override
public Object convert(Object o, Class aClass, Object o1) {
if (o instanceof Enum) {
return o.toString();
}else {
return o;
}
}
}
BeanCopier
使用这个转换器时完全按照这个转换器来转化,所以,如果src
和target
其他属性都一样就直接返回
//设置为true才按照自定义转换器来转化两个类
BeanCopier copier = BeanCopier.create(BaseInfoForm.class, TbContManBasic.class, true);
Enum2StringConverter converter = new Enum2StringConverter();
//manContractForm.getBaseInfoForm(): src, tbContManBasic: target, converter:转换器
copier.copy(manContractForm.getBaseInfoForm(), tbContManBasic, converter);