一、mybatis 枚举映射四大实现方案
1. 基础序数映射(enumtypehandler)
// java 枚举类 public enum orderstatus { new, paid, delivered, cancelled; } // mybatis实体类映射 public class order { private orderstatus status; // getters/setters }
mapper xml 配置:
<resultmap id="orderresultmap" type="order"> <result property="status" column="status"/> </resultmap>
mysql 表设计:
create table orders ( id int primary key auto_increment, status tinyint comment '0-新订单,1-已支付,2-已发货,3-已取消' );
优缺点:
- ✅ 零配置自动生效
- ⚠️ 无法修改枚举顺序
- ⚠️ 数据库可读性差
2. 枚举名称映射(enumordinaltypehandler)
// mybatis 配置文件 <typehandlers> <typehandler handler="org.apache.ibatis.type.enumtypehandler" javatype="com.example.orderstatus"/> </typehandlers> // 或全局配置 <settings> <setting name="defaultenumtypehandler" value="org.apache.ibatis.type.enumtypehandler"/> </settings>
表设计:
alter table orders modify column status varchar(20) comment '订单状态';
适配枚举改动:
public enum orderstatus { new("新订单"), paid("已支付"), delivered("已发货"), cancelled("已取消"); private final string desc; orderstatus(string desc) { this.desc = desc; } }
3. 自定义类型处理器(typehandler)
3.1 基于字符串的转换
@mappedtypes(orderstatus.class) public class orderstatushandler extends basetypehandler<orderstatus> { @override public void setnonnullparameter(preparedstatement ps, int i, orderstatus status, jdbctype jdbctype) { ps.setstring(i, status.name()); } @override public orderstatus getnullableresult(resultset rs, string columnname) { string code = rs.getstring(columnname); return orderstatus.valueof(code); } // 其他getnullableresult方法... }
3.2 基于编码的转换(推荐)
@mappedtypes(usertype.class) public class usertypehandler extends basetypehandler<usertype> { @override public void setnonnullparameter(preparedstatement ps, int i, usertype usertype, jdbctype jdbctype) { ps.setstring(i, usertype.getcode()); } @override public usertype getnullableresult(resultset rs, string columnname) { string code = rs.getstring(columnname); return usertype.fromcode(code); } }
注册处理器:
<typehandlers> <typehandler handler="com.example.handler.usertypehandler"/> </typehandlers>
实体类使用:
public class user { @tablefield(typehandler = usertypehandler.class) private usertype type; }
4. 枚举值关联表方案
create table user_types ( id tinyint primary key auto_increment, code char(2) unique not null, name varchar(20) not null ); insert into user_types (code, name) values ('a', '管理员'), ('e', '编辑'), ('u', '普通用户');
mapper xml 查询:
<resultmap id="userresultmap" type="user"> <result property="id" column="id"/> <association property="type" column="type_code" select="selectusertypebycode"/> </resultmap> <select id="selectusertypebycode" resulttype="usertype"> select code, name as description from user_types where code = #[code] </select>
二、mybatis-plus 高级枚举映射
1. 内置枚举处理器
public enum productstatus implements ienum<integer> { draft(0), published(1), archived(2); private final int value; productstatus(int value) { this.value = value; } @override public integer getvalue() { return this.value; } } // 实体类使用 public class product { private productstatus status; }
全局配置(application.yml):
mybatis-plus: configuration: default-enum-type-handler: com.baomidou.mybatisplus.core.handlers.mybatisenumtypehandler
2. 字段注解映射
public class product { @tablefield(value = "status", typehandler = productstatushandler.class) private productstatus status; }
3. json格式存储枚举属性
public class order { @tablefield(typehandler = jsontypehandler.class) private map<orderstatus, integer> statusstatistics; }
json存储结构:
{ "new": 10, "paid": 5, "delivered": 3 }
三、枚举映射最佳实践方案
1. 防御式枚举设计
public enum orderstatus { new("n"), paid("p"), delivered("d"), cancelled("c"); private final string code; private static final map<string, orderstatus> code_map = new hashmap<>(); static { for (orderstatus status : values()) { code_map.put(status.code, status); } } public static orderstatus fromcode(string code) { orderstatus status = code_map.get(code); if (status == null) { if (code == null) return null; string cleancode = code.trim().touppercase(); return optional.ofnullable(code_map.get(cleancode)) .orelsethrow(() -> new illegalargumentexception( "无效状态码: " + code)); } return status; } }
2. 枚举基类设计
public interface enumcode { string getcode(); string getdescription(); } public abstract class baseenumhandler<e extends enum<e> & enumcode> extends basetypehandler<e> { private final class<e> type; private final map<string, e> enummap; public baseenumhandler(class<e> type) { this.type = type; this.enummap = arrays.stream(type.getenumconstants()) .collect(collectors.tomap(enumcode::getcode, e -> e)); } @override public void setnonnullparameter(preparedstatement ps, int i, e parameter, jdbctype jdbctype) { ps.setstring(i, parameter.getcode()); } @override public e getnullableresult(resultset rs, string columnname) { string code = rs.getstring(columnname); return code == null ? null : enummap.get(code); } }
四、实战应用场景
1. 多状态组合(bit存储)
public enum permission { read(1), write(2), delete(4), execute(8); private final int bitvalue; // 存储所有权限值到单个整数 public static int encode(set<permission> permissions) { return permissions.stream() .maptoint(p -> p.bitvalue) .sum(); } public static set<permission> decode(int value) { return arrays.stream(values()) .filter(p -> (value & p.bitvalue) != 0) .collect(collectors.toset()); } } // mybatis类型处理器 public class permissionsethandler extends basetypehandler<set<permission>> { @override public void setnonnullparameter(preparedstatement ps, int i, set<permission> perms, jdbctype jdbctype) { ps.setint(i, permission.encode(perms)); } @override public set<permission> getnullableresult(resultset rs, string columnname) { int value = rs.getint(columnname); return rs.wasnull() ? collections.emptyset() : permission.decode(value); } }
2. 动态状态机验证
public class orderservice { @transactional public void updateorderstatus(long orderid, orderstatus newstatus) { order order = ordermapper.selectbyid(orderid); orderstatus oldstatus = order.getstatus(); if (!oldstatus.isallowedtransition(newstatus)) { throw new illegalstateexception("状态转换非法: " + oldstatus + " -> " + newstatus); } order.setstatus(newstatus); ordermapper.updatebyid(order); } } // 枚举中定义状态转移规则 public enum orderstatus { new { @override public boolean isallowedtransition(orderstatus newstatus) { return newstatus == paid || newstatus == cancelled; } }, // 其他状态定义... }
五、性能优化技巧
静态映射缓存:
public abstract class cachedenumhandler<e extends enum<e> & enumcode> extends basetypehandler<e> { private final map<string, e> codeenummap; private final map<e, string> enumcodemap; public cachedenumhandler(class<e> enumclass) { e[] enums = enumclass.getenumconstants(); codeenummap = arrays.stream(enums) .collect(collectors.tomap(enumcode::getcode, e -> e)); enumcodemap = arrays.stream(enums) .collect(collectors.tomap(e -> e, enumcode::getcode)); } }
批量处理优化:
@mapper public interface batchmapper { @insert("<script>" + "insert into users (type, name) values " + "<foreach item='item' collection='list' separator=','>" + "(#{item.type, typehandler=com.example.usertypehandler}, #{item.name})" + "</foreach>" + "</script>") int batchinsertusers(@param("list") list<user> users); }
数据库约束优化:
-- mysql enum 类型约束 status enum('new','paid','delivered','cancelled') not null default 'new' comment '订单状态' -- postgresql检查约束 alter table orders add constraint status_check check (status in ('new', 'paid', 'delivered', 'cancelled'));
六、错误解决方案手册
1. 序列化问题修复
// 添加枚举序列化配置 @jsonformat(shape = jsonformat.shape.object) public enum orderstatus implements enumcode { // ... } // 或自定义序列化器 public class enumcodeserializer extends stdserializer<enumcode> { public enumcodeserializer() { super(enumcode.class); } @override public void serialize(enumcode value, jsongenerator gen, serializerprovider provider) { gen.writestartobject(); gen.writestringfield("code", value.getcode()); gen.writestringfield("description", value.getdescription()); gen.writeendobject(); } }
2. 国际化方案
public interface localizedenum { string getcode(); default string getmessage(locale locale) { resourcebundle bundle = resourcebundle.getbundle( "enum_messages", locale); return bundle.getstring(this.getclass().getsimplename() + "." + getcode()); } } // 多语言资源文件 // en_us.properties usertype.a=administrator usertype.e=editor usertype.u=user // zh_cn.properties usertype.a=管理员 usertype.e=编辑 usertype.u=普通用户
总结:mybatis枚举映射决策树
graph td a[需要映射枚举] --> b{是否简单状态值?} b --> |是| c{是否确定永不修改顺序?} c --> |是| d[使用enumtypehandler默认序数映射] c --> |否| e[使用enumordinaltypehandler名称映射] b --> |否| f{是否需要业务编码?} f --> |是| g[自定义typehandler+编码设计] f --> |否| h{是否多语言/复杂属性?} h --> |是| i[关联表映射方案] h --> |否| j[直接使用mybatis-plus枚举方案]
企业级应用建议:
- 选择自定义编码映射作为默认方案
- 对性能敏感的常量枚举使用序数映射
- 需要多语言支持的使用关联表映射
- 组合状态使用bit存储+解码方案
遵循这些模式,可构建出健壮且易维护的枚举持久化层,完美平衡数据库高效存储与业务代码的可读性需求。
到此这篇关于mybatis 枚举映射的实现示例的文章就介绍到这了,更多相关mybatis 枚举映射内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论