介绍
本篇内容主要讲解“MyBatis数据库字段该如何映射Java枚举”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“MyBatis数据库字段该如何映射Java枚举”吧!
有时候我们需要将数据库的字段对Java的枚举类型进行映射,比如说我们有一个汽车配件类型的枚举
public enum ProductType implements Localisable {类型1(“配件“),,,,,TYPE2(“车品“),,,,,private String 价值;,,,,private ProductType (String 价值),{=this.value 价值;,,,,}@Override ,,, public String getValue (), {return this.value;,,,,} }
该枚举类型实现了一个接口
public interface Localisable { ,,,String getValue ();}
有一个配件分类的实体类,包含了该枚举字段(此处只包含部分字段属性)
/* *, *,配件分类,*/@AllArgsConstructor@NoArgsConstructorpublic class ProviderProductLevel {@Getter ,,, @Setter ,,, private Long id;,,,, @Getter ,,, @Setter ,,, private String 代码;,,,,@Getter ,,, @Setter ,,, private String 名字,,,,,@Getter ,,, @Setter ,,, private Integer 分类;,,,,@Getter ,,, @Setter ,,, private Integer 水平;,,,,@Getter ,,, @Setter ,,, private ProductType productType;,,,, @Getter ,,, @Setter ,,, private String pictureUrl; }
而在数据库中的表结构如下
dao方法如下(通过id查找一个配件分类,并实例化)
@Mapperpublic interface LevelDao { ProviderProductLevel findLevel1(Long id);}
mapper映射文件如下
<?xml version="1.0" encoding="UTF-8" ?>
我们可以看到这里有一个映射处理器typeHandler="com.cloud.productprovider.untils.DbEnumTypeHandler"
该映射处理器的代码如下
@AllArgsConstructorpublic class DbEnumTypeHandler extends BaseTypeHandler{private Class type; @Override public void setNonNullParameter(PreparedStatement ps, int i, Localisable parameter, JdbcType jdbcType) throws SQLException { ,,,,,,,ps.setString(我parameter.getValue ()),,,,,} @Override ,,, public Localisable getNullableResult (ResultSet , rs, String columnName), throws SQLException { null null null null null null null null null MyBatis数据库字段该如何映射Java枚举