Mybatis实战之自定义TypeHandler处理枚举
在Mybatis中,处理枚举类的TypeHandler有两个:
- EnumTypeHandler: 用于保存枚举名
- EnumOrdinalTypeHandler: 用于保存枚举的序号。
在实际项目中,以上往往不能满足我们的需求。
需求分析
枚举需要包含两个属性,label(用于显示), value(实际的枚举值)。数据库保存枚举值(value)。
这很明显Mybatis提供的两个枚举TypeHandler不能满足我们的需求。此时,我们可以自定义一个通用的枚举TypeHandler来满足我们的需求。
自定义枚举TypeHandler
通用枚举DisplayedEnum
public interface DisplayedEnum {
String DEFAULT_VALUE_NAME = "value";
String DEFAULT_LABEL_NAME = "label";
default Integer getValue() {
Field field = ReflectionUtils.findField(this.getClass(), DEFAULT_VALUE_NAME);
if (field == null)
return null;
try {
field.setAccessible(true);
return Integer.parseInt(field.get(this).toString());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@JsonValue
default String getLabel() {
Field field = ReflectionUtils.findField(this.getClass(), DEFAULT_LABEL_NAME);
if (field == null)
return null;
try {
field.setAccessible(true);
return field.get(this).toString();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
static <T extends Enum<T>> T valueOfEnum(Class<T> enumClass, Integer value) {
if (value == null)
throw new IllegalArgumentException("DisplayedEnum value should not be null");
if (enumClass.isAssignableFrom(DisplayedEnum.class))
throw new IllegalArgumentException("illegal DisplayedEnum type");
T[] enums = enumClass.getEnumConstants();
for (T t: enums) {
DisplayedEnum displayedEnum = (DisplayedEnum)t;
if (displayedEnum.getValue().equals(value))
return (T) displayedEnum;
}
throw new IllegalArgumentException("cannot parse integer: " + value + " to " + enumClass.getName());
}
}
说明:
普通枚举类通过实现DisplayedEnum接口,就可以:
- 通过getValue()获取枚举值。
- 通过getLabel()获取枚举的label属性。
- 通过valueOfEnum()将Integer值转换为指定的枚举类型。
普通枚举类
public enum CommonsType implements DisplayedEnum {
NORMAL("正常", 0), INVALID("无效", 1);
String label;
Integer value;
private CommonsType(String label, Integer value) {
this.label = label;
this.value = value;
}
}
以上就是一个普通枚举类的示例。
自定义枚举TypeHandler
@MappedJdbcTypes(value = JdbcType.TINYINT, includeNullJdbcType = true)
public class DefaultEnumTypeHandler extends BaseTypeHandler<DisplayedEnum> {
private Class<DisplayedEnum> type;
public DefaultEnumTypeHandler(){};
public DefaultEnumTypeHandler(Class<DisplayedEnum> type) {
if (type == null) throw new IllegalArgumentException("Type argument cannot be null");
this.type = type;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, DisplayedEnum parameter, JdbcType jdbcType)
throws SQLException {
ps.setInt(i, parameter.getValue());
}
@Override
public DisplayedEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
return convert(rs.getInt(columnName));
}
@Override
public DisplayedEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return convert(rs.getInt(columnIndex));
}
@Override
public DisplayedEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return convert(cs.getInt(columnIndex));
}
private DisplayedEnum convert(int status){
DisplayedEnum[] objs = type.getEnumConstants();
for(DisplayedEnum em: objs){
if(em.getValue() == status){
return em;
}
}
return null;
}
}
使用我们自定义的DefaultEnumTypeHandler
由于Mybatis默认在处理枚举类型的时候会使用EnumTypeHandler(只保存及转换枚举类型的名字), 因此,我们需要手动指定使用DefaultEnumTypeHandler。示例如下:
<resultMap id="xxx" type="xxx">
...
<result column="type" jdbcType="TINYINT" property="type" typeHandler="xxx.xxx.xxx.DefaultEnumTypeHandler" />
...
</resultMap>
即我们需要通过使用typeHandler来指定。
小结
以上是我们应用在实际项目中的一个对于Mybatis处理枚举类的方案。我看大多数人也都是这样在用。然而,在实际项目中,我们会发现随着枚举类的增多,这样写起来会很繁琐。我看了一下网络上似乎也没人处理这种情况。那么,下一篇文章将针对这种情况进行处理。
我的博客: javafan.cn
Mybatis实战之自定义TypeHandler处理枚举的更多相关文章
- 使用mybatis中的自定义TypeHandler处理PostgreSQL中的Json类型字段
业务扩展字段在PostgreSQL数据库中经常会使用json格式的数据来存储,然而mybatis默认是没有实现json类型字段对应的TypeHandler,所以一般我们需要自定义mybatis的Typ ...
- Mybatis实战之TypeHandler高级进阶
上篇文章分享了在项目实战中自定义Mybatis的TypeHandler来处理枚举类型.文章结尾也指出了美中不足之处,那就是每次都需要指定我们自定义的枚举TypeHandler. 随着项目枚举类型的增多 ...
- MyBatis使用自定义TypeHandler转换类型的实现方法
From: http://www.manongjc.com/article/15577.html 这篇文章主要介绍了MyBatis使用自定义TypeHandler转换类型的实现方法,本文介绍使用Typ ...
- MyBatis使用自定义TypeHandler转换类型
MyBatis虽然有很好的SQL执行性能,但毕竟不是完整的ORM框架,不同的数据库之间SQL执行还是有差异. 笔者最近在升级 Oracle 驱动至 ojdbc 7 ,就发现了处理DATE类型存在问题. ...
- MyBatis实战之配置
MyBatis最重要的配置也就两个,一个是mybatis-config.xml,又称MyBatis的全局配置,另一个就是XXXDao.xml或XXXMapper.xml映射配置. mybatis-co ...
- mybatis类型转换器 - 自定义全局转换enum
在数据模型.接口参数等场景部分属性参数为一些常量值,比如性别:男.女.若是定义成int或String类型,于是类型本身的范围太宽,要求使用者需要了解底层的业务方可知如何传值,那整体来看增加沟通成本,对 ...
- 【转】mybatis实战教程(mybatis in action),mybatis入门到精通
MyBatis 目录(?)[-] mybatis实战教程mybatis in action之一开发环境搭建 mybatis实战教程mybatis in action之二以接口的方式编程 mybatis ...
- mybatis实战教程(mybatis in action),mybatis入门到精通
转自:http://www.yihaomen.com/article/java/302.htm (读者注:其实这个应该叫做很基础的入门一下下,如果你看过hibernate了那这个就非常的简单) (再加 ...
- mybatis实战教程(mybatis in action),mybatis入门到精通(转)
转自:http://www.yihaomen.com/article/java/302.htm (读者注:其实这个应该叫做很基础的入门一下下,如果你看过Hibernate了那这个就非常的简单) (再加 ...
随机推荐
- 苹果应用商店AppStore审核中文指南 分类: ios相关 app相关 2015-07-27 15:33 84人阅读 评论(0) 收藏
目录 1. 条款与条件 2. 功能 3. 元数据.评级与排名 4. 位置 5. 推送通知 6. 游戏中心 7. 广告 8. 商标与商业外观 9. 媒体内容 10. 用户界面 11. 购买与货币 12. ...
- IOS开发中Xcode常用插件安装与管理(转)
XCode中插件管理工具:Alcatraz 转自http://www.cocoachina.com/industry/20140506/8325.html 苹果现在的成绩得益于其始终如一的坚持. ...
- Hooking Android System Calls for Pleasure and Benefit
The Android kernel is a powerful ally to the reverse engineer. While regular Android apps are hopele ...
- ARM处理器工作模式
学习ARM处理器参考的首选资料是ARM Architecture Reference Manual,是最专业权威的学习资料. ARM处理器共有7种工作模式,如表1-1和1-2所示: 表1-1 处理器工 ...
- 用Django Rest Framework和AngularJS开始你的项目
Reference: http://blog.csdn.net/seele52/article/details/14105445 译序:虽然本文号称是"hello world式的教程&quo ...
- Unable to list the users SQLSTATE =S0002
powerdesinger mysql 反向工程时报错 解决方案: database ->change the Target DNMS 修改DBMS为mysql 的对应版本 修改后,点击确定即可 ...
- iOS 错误及解决汇总
1. iOS 错误 之 http请求 2. iOS 错误 之 Unexpected interface name 'HomeListCell': expected expression 3. iOS ...
- GOLang(第二篇 发起一个Http请求)
import ( "net/http" "net/url" ) //发送一个简单的get请求 func GetRequest { //联系使用 make(map ...
- CSS BUG 总结
1.IE7 容器使用了滚动条 其子元素中使用 position:relative ,position变成了fixed,从而不随容器的滚动条滚动; 解决: 在其容器元素的属性中也加入 position ...
- Hdu-2112 HDU Today (单源多点最短路——Dijsktra算法)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2112 题目大意:给你N个公交车站,起点,终点,各站之间的距离,求起点到终点之间的最短距离.(起点终点相 ...