mybatis mysql枚举类型转换_springboot + mybatis自定义枚举类型转换

本文参考了网上文章,同时结合了自己的使用。

需要枚举类型转换的过程

1. 前台提交的数据(如从form表单提交的数据) -> controller参数(如实体类)

2. 实体类 -> 数据库 (该过程通常发生在Dao层)

3. 数据库 -> 实体类 (该过程通常发生在Dao层)

实体类package com.entity;

import com.enumeration.Level;

/**

* 用户

*/

public class User {// get、set方法省略

private String id;

private String name; // 名字

private Level level; // 等级

}

枚举package com.enumeration;

public enum Level implements BaseEnum{

ORDINARY(1, "普通会员"), GOLDEN(2, "黄金会员");

private Integer value; // 值

private String description; // 描述

private Level(int value, String description) {

this.value = value;

this.description = description;

}

@Override

public Integer getValue() {

return value;

}

public String getDescription() {

return description;

}

}package com.enumeration;

public interface BaseEnum {

Integer getValue();

}

1.前台提交的数据 -> controller参数package com.converter;

import java.util.HashMap;

import java.util.Map;

import java.util.WeakHashMap;

import org.springframework.core.convert.converter.Converter;

import org.springframework.core.convert.converter.ConverterFactory;

import com.enumeration.BaseEnum;

/**

* 枚举类型转换

*/

public class BaseEnumConverterFactory implements ConverterFactory {

@SuppressWarnings("rawtypes")

private static final Map converterMap = new WeakHashMap<>();

@SuppressWarnings({ "rawtypes", "unchecked" })

@Override

public  Converter getConverter(Class targetType) {

Converter result = converterMap.get(targetType);

if(result == null) {

result = new IntegerStrToEnum(targetType);

converterMap.put(targetType, result);

}

return result;

}

class IntegerStrToEnum implements Converter {

@SuppressWarnings("unused")

private final Class enumType;

private Map enumMap = new HashMap<>();

public IntegerStrToEnum(Class enumType) {

this.enumType = enumType;

T[] enums = enumType.getEnumConstants();

for(T e : enums) {

enumMap.put(e.getValue() + "", e);

}

}

@Override

public T convert(String source) {

T result = enumMap.get(source);

if(result == null) {

throw new IllegalArgumentException("No element matches " + source);

}

return result;

}

}

}

注册ConverterFactorypackage com.config;

import org.springframework.context.annotation.Configuration;

import org.springframework.format.FormatterRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.converter.BaseEnumConverterFactory;

/**

* mvc 配置

*/

@Configuration

public class WebAppConfigurer implements WebMvcConfigurer {

@Override

public void addFormatters(FormatterRegistry registry) {

// 注册ConverterFactory(类型转换器工厂)

registry.addConverterFactory(new BaseEnumConverterFactory());

}

}

前台传递参数

添加用户

用户名字

用户等级

普通会员

黄金会员

controller接收参数/**

* 添加用户

*

* @param user

* @return

*/

@RequestMapping(method = RequestMethod.POST)

public String Add(User user) {

// 代码省略

}

2.实体类 -> 数据库

类型转换实现类package com.typeHandler;

import java.sql.CallableStatement;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.HashMap;

import java.util.Map;

import org.apache.ibatis.type.BaseTypeHandler;

import org.apache.ibatis.type.JdbcType;

import com.enumeration.BaseEnum;

public class BaseEnumTypeHandler extends BaseTypeHandler {

private Class enumType;

private Map enumMap = new HashMap<>();

public BaseEnumTypeHandler(Class type) {

if (type == null)

throw new IllegalArgumentException("Type argument cannot be null");

this.enumType = type;

E[] enums = enumType.getEnumConstants();

if (enums == null)

throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");

for (E e : enums) {

enumMap.put(e.getValue(), e);

}

}

@Override

public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {

ps.setInt(i, parameter.getValue());

}

@Override

public E getNullableResult(ResultSet rs, String columnName) throws SQLException {

return get(rs.getInt(columnName));

}

@Override

public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {

return get(rs.getInt(columnIndex));

}

@Override

public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {

return get(cs.getInt(columnIndex));

}

private E get(Integer v) {

if (v == null) {

return null;

}

return this.enumMap.get(v);

}

}

mapper文件中对应枚举的字段要指定typeHandler,如

SELECT UUID()

INSERT INTO user (id, name, level)

VALUES

(#{id,jdbcType=VARCHAR},

#{name,jdbcType=VARCHAR},

#{level,jdbcType=INTEGER,typeHandler=com.typeHandler.BaseEnumTypeHandler}

)

3.数据库 -> 实体类

类型转换实现类和2中一致。

mapper文件中,对应枚举的字段要指定javaType和typeHandler,如

javaType="com.enumeration.Level" typeHandler="com.typeHandler.BaseEnumTypeHandler" />

SELECT * from USER

项目下载地址:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值