将数据库中查询的 alarm_type (tiny int类型)转换为java的AlarmTypeEnum类型
AlarmTypeEnum字段
1、要转换的枚举定义
import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * 告警类型 * 目前支持邮件告警和,短信告警 */ public enum AlarmTypeEnum { /** * 短信告警 */ SMS((short) 1), /** * 邮件告警 */ EMAIL((short) 2); /** * 数据库中存储的码号,号码不能重复(注意此处应code和数据库中的一致) */ private short code; private static Map<Short, AlarmTypeEnum> alarmTypes; static { alarmTypes = new HashMap<>(); AlarmTypeEnum[] values = AlarmTypeEnum.values(); Arrays.stream(values).forEach(alarmTypeEnum -> alarmTypes.put(alarmTypeEnum.getCode(), alarmTypeEnum)); } AlarmTypeEnum(short code) { this.code = code; } public short getCode() { return code; } public static AlarmTypeEnum parseCode(short code) { return alarmTypes.get(code); } public static void main(String[] args) { System.out.println(AlarmTypeEnum.parseCode((short) 2)); } }
1、请求实体
import lombok.Data; import lombok.ToString; @ToString @Data public class AlarmInfoDTO { /** * 告警类型 */ private AlarmTypeEnum alarmType; /** * 告警手机号 */ private String alarmPhone; /** * 告警的emali邮箱 */ private String alarmEmail; public void setAlarmType(short alarmTypeCode) { this.alarmType = AlarmTypeEnum.parseCode(alarmTypeCode); } }
2、CpMapper.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.test.base.dao.CpMapper"> <resultMap id="AlarmInfoMap" type="com.sms.cloud.base.dto.AlarmInfoDTO"> <result column="alarm_type" property="alarmType" javaType="java.lang.Short"/> <result column="alarm_phone" property="alarmPhone"/> <result column="alarm_email" property="alarmEmail"/> </resultMap> <select id="getAlarmInfo" parameterType="java.lang.Integer" resultMap="AlarmInfoMap"> select alarm_type,alarm_phone,alarm_email from dx_sms_cp where id=#{cpid,jdbcType=INTEGER}; </select> </mapper>