有时候我们需要将数据库的字段对Java的枚举类型进行映射,比如说我们有一个汽车配件类型的枚举
public enum ProductType implements Localisable { TYPE1("配件"), TYPE2("车品"); private String value; private ProductType(String value) { this.value = value; } @Override public String getValue() { return this.value; } }
该枚举类型实现了一个接口
public interface Localisable { String getValue(); }
有一个配件分类的实体类,包含了该枚举字段(此处只包含部分字段属性)
/** * 配件分类 */ @AllArgsConstructor @NoArgsConstructor public class ProviderProductLevel { @Getter @Setter private Long id; @Getter @Setter private String code; @Getter @Setter private String name; @Getter @Setter private Integer sort; @Getter @Setter private Integer level; @Getter @Setter private ProductType productType; @Getter @Setter private String pictureUrl; }
而在数据库中的表结构如下
dao方法如下(通过id查找一个配件分类,并实例化)
@Mapper public interface LevelDao { ProviderProductLevel findLevel1(Long id); }
mapper映射文件如下
xml version="1.0" encoding="UTF-8" ?> mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">namespace="com.cloud.productprovider.dao.LevelDao"> id="level1Map" type="com.cloud.productprovider.composite.ProviderProductLevel"> property="id" column="id" /> property="code" column="code" /> property="name" column="name" /> property="sort" column="sort" /> property="productType" column="product_type" typeHandler="com.cloud.productprovider.untils.DbEnumTypeHandler" />
我们可以看到这里有一个映射处理器typeHandler="com.cloud.productprovider.untils.DbEnumTypeHandler"
该映射处理器的代码如下
@AllArgsConstructor public class DbEnumTypeHandler extends BaseTypeHandler{ private Class type; @Override public void setNonNullParameter(PreparedStatement ps, int i, Localisable parameter, JdbcType jdbcType) throws SQLException { ps.setString(i,parameter.getValue()); } @Override public Localisable getNullableResult(ResultSet rs, String columnName) throws SQLException { String value = rs.getString(columnName); if (rs.wasNull()) { return null; }else { return convert(value); } } @Override public Localisable getNullableResult(ResultSet rs, int columnIndex) throws SQLException { String value = rs.getString(columnIndex); if (rs.wasNull()) { return null; }else { return convert(value); } } @Override public Localisable getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { String value = cs.getString(columnIndex); if (cs.wasNull()) { return null; }else { return convert(value); } } private Localisable convert(String value) { Localisable[] dbEnums = type.getEnumConstants(); for (Localisable dbEnum : dbEnums) { if (dbEnum.getValue().equals(value)) { return dbEnum; } } return null; } }
经测试返回的结果对象的Json字符串如下
{"code":"0000001","id":1,"name":"油品","productType":"TYPE1","sort":1}