首页新闻找找看学习计划

spring boot mybatis 枚举错误

0
悬赏园豆:50 [待解决问题]

spring boot mybatis 枚举错误

  • 今天遇到一个问题,解决了好几个小时,没有搞定,有大佬可以帮我看下吗?万分感谢,枚举映射,在idea中可以使用,
    部署使用java -jar 方式就报错
  • jdk1.8
  • mybatis3.0.7.1
  • application.yml环境为prod
mybatis-plus:
    #枚举
    typeHandlersPackage: com.xxx.common.module.handler
  1. Enum代码
/**
 * Enum - 状态
 *
 * @author xxx
 * @version 1.0.0
 */
@JSONType(serializeEnumAsJavaBean = true)
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum StatusEnum implements BaseEnum<StatusEnum, Integer> {

    /** 删除 */
    删除(-1, "删除"),
    /** 无效 */
    无效(0, "无效"),
    /** 有效 */
    有效(1, "有效");

    /**
     * 值.
     */
    private Integer value;
    /**
     * 名称.
     */
    private String name ;

    static {
        subClass.add(StatusEnum.class);
    }

    StatusEnum(Integer value, String name) {
        this.value = value;
        this.name = name;
    }

    @Override
    public Integer getValue() {
        return value;
    }

    public void setValue(Integer value) {
        this.value = value;
    }

    @Override
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //根据key获取枚举
    public static StatusEnum getEnumByValue(Integer value){
        if (null == value){
            return null;
        }
        for(StatusEnum e: StatusEnum.values()){
            if(e.getValue().equals(value)){
                return e;
            }
        }
        return null;
    }
}
  1. 枚举转换处理器
package com.xxx.common.module.handler;

import com.xxx.common.module.enums.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 枚举转换处理器
 *
 * @author xxx
 * @version 1.0.0
 */
@Slf4j
@MappedTypes(value = {StatusEnum.class})
public final class BaseEnumTypeHandler<E extends BaseEnum> extends BaseTypeHandler<E> {

    private Class<E> type;
    private E[] enums;

    public BaseEnumTypeHandler() {
    }

    public BaseEnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
        this.enums = this.type.getEnumConstants();
        if (this.enums == null) {
            throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        //BaseTypeHandler 进行非空校验
        log.debug("index : {}, parameter : {},jdbcType : {} ", i, parameter.getValue(), jdbcType);

        if (jdbcType == null) {
            ps.setObject(i, parameter.getValue());
        } else {
            ps.setObject(i, parameter.getValue(), jdbcType.TYPE_CODE);
        }
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object code = rs.getObject(columnName);

        if (rs.wasNull()) {
            return null;
        }

        return getEnmByCode(code);
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object code = rs.getObject(columnIndex);
        if (rs.wasNull()) {
            return null;
        }

        return getEnmByCode(code);
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object code = cs.getObject(columnIndex);
        if (cs.wasNull()) {
            return null;
        }

        return getEnmByCode(code);
    }

 
    private E getEnmByCode(Object code) {

        if (code == null) {
            throw new NullPointerException("the result code is null " + code);
        }

        if (code instanceof Integer) {
            for (E e : enums) {
                if (e.getValue() == code) {
                    return e;
                }
            }
            throw new IllegalArgumentException("Unknown enumeration type , please check the enumeration code :  " + code);
        }


        if (code instanceof String) {
            for (E e : enums) {
                if (code.equals(e.getValue())) {
                    return e;
                }
            }
            throw new IllegalArgumentException("Unknown enumeration type , please check the enumeration code :  " + code);
        }

        throw new IllegalArgumentException("Unknown enumeration type , please check the enumeration code :  " + code);
    }
}
  1. 报错信息
2020-01-20 02:45:35.879 ERROR 2472 --- [nio-8081-exec-1] c.l.exception.RRExceptionHandler         : nested exception is org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'status' from result set.  Cause: java.lang.IllegalArgumentException: No enum constant com.xxx.common.module.enums.StatusEnum.1

* org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'status' from result set.  Cause: java.lang.IllegalArgumentException: No enum constant com.xxx.common.module.enums.StatusEnum.1
*         at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:77)
*         at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446)
*         at com.sun.proxy.$Proxy132.selectList(Unknown Source)
*         at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:230)
*         at com.baomidou.mybatisplus.core.override.PageMapperMethod.executeForMany(PageMapperMethod.java:173)
*         at com.baomidou.mybatisplus.core.override.PageMapperMethod.execute(PageMapperMethod.java:86)
*         at com.baomidou.mybatisplus.core.override.PageMapperProxy.invoke(PageMapperProxy.java:64)
*         at com.sun.proxy.$Proxy137.selectList(Unknown Source)
*         at com.baomidou.mybatisplus.extension.service.impl.ServiceImpl.getOne(ServiceImpl.java:259)
*         at com.baomidou.mybatisplus.extension.service.IService.getOne(IService.java:230)
*         at com.xxx.common.module.service.impl.AppServiceImpl.queryByAppKey(AppServiceImpl.java:100)
*         at com.xxx.common.module.service.impl.AppServiceImpl$$FastClassBySpringCGLIB$$9380a940.invoke(<generated>)
*         at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
*         at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:684)
*         at com.xxx.common.module.service.impl.AppServiceImpl$$EnhancerBySpringCGLIB$$307b01.queryByAppKey(<generated>)
*         at com.xxx.common.module.service.impl.AppInfoServiceImpl.validateBaseApi(AppInfoServiceImpl.java:141)
*         at com.xxx.common.module.service.impl.AppInfoServiceImpl.appInfo(AppInfoServiceImpl.java:157)
*         at com.xxx.common.module.service.impl.AppInfoServiceImpl$$FastClassBySpringCGLIB$$2bb67632.invoke(<generated>)
*         at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
*         at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:684)
*         at com.xxx.common.module.service.impl.AppInfoServiceImpl$$EnhancerBySpringCGLIB$$8bd88917.appInfo(<generated>)
*         at com.xxx.controller.ApiAppProductController.list(ApiAppProductController.java:79)
*         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
*         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
*         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
*         at java.lang.reflect.Method.invoke(Method.java:483)
*         at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
*         at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
*         at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
*         at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
*         at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
*         at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
*         at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
*         at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
*         at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
*         at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
*         at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
*         at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
*         at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
*         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
*         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
*         at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
*         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
*         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
*         at com.xxx.common.xss.XssFilter.doFilter(XssFilter.java:24)
*         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
*         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
*         at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
*         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
*         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
*         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
*         at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
*         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
*         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
*         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
*         at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
*         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
*         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
*         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
*         at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
*         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
*         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
*         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
*         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
*         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
*         at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
*         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
*         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
*         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
*         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
*         at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
*         at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
*         at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
*         at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
*         at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
*         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
*         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
*         at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
*         at java.lang.Thread.run(Thread.java:745)
* Caused by: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'status' from result set.  Cause: java.lang.IllegalArgumentException: No enum constant com.xxx.common.module.enums.StatusEnum.1
*         at org.apache.ibatis.type.BaseTypeHandler.getResult(BaseTypeHandler.java:68)
*         at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.applyAutomaticMappings(DefaultResultSetHandler.java:520)
*         at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getRowValue(DefaultResultSetHandler.java:401)
*         at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValuesForSimpleResultMap(DefaultResultSetHandler.java:355)
*         at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValues(DefaultResultSetHandler.java:330)
*         at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSet(DefaultResultSetHandler.java:303)
*         at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSets(DefaultResultSetHandler.java:196)
*         at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:64)
*         at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79)
*         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
*         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
*         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
*         at java.lang.reflect.Method.invoke(Method.java:483)
*         at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:63)
*         at com.sun.proxy.$Proxy200.query(Unknown Source)
*         at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63)
*         at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:326)
*         at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156)
*         at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:136)
*         at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
*         at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
*         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
*         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
*         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
*         at java.lang.reflect.Method.invoke(Method.java:483)
*         at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433)
*         ... 77 common frames omitted
* Caused by: java.lang.IllegalArgumentException: No enum constant com.xxx.common.module.enums.StatusEnum.1
*         at java.lang.Enum.valueOf(Enum.java:238)
*         at org.apache.ibatis.type.EnumTypeHandler.getNullableResult(EnumTypeHandler.java:49)
*         at org.apache.ibatis.type.EnumTypeHandler.getNullableResult(EnumTypeHandler.java:26)
*         at org.apache.ibatis.type.BaseTypeHandler.getResult(BaseTypeHandler.java:66)
*         ... 102 common frames omitted
pakl的主页 pakl | 初学一级 | 园豆:50
提问于:2020-01-20 03:23
< >
分享
所有回答(2)
0

5.配置文件

添加配置type-handlers-package,指向处理器的包名位置

该配置项 位于(mybatis或mybatis-plus)下

'''
mybatis-plus:
mapper-locations: classpath:/cn/edu//xml/Mapper.xml
type-aliases-package: cn.edu.model
type-aliases-super-type: cn.edu.model.BaseModel
global-config:
db-config:
field-strategy: ignored
#全局默认主键类型
id-type: id_worker
# 逻辑已删除值
logic-delete-value: 1
# 逻辑未删除值
logic-not-delete-value: 0
# 数据库类型
db-type: mysql
#缓存sql解析
sql-parser-cache: true
configuration:
# sql执行语句打印
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#自动驼峰命名规则
map-underscore-to-camel-case: true
#自定义类型处理器的包名
type-handlers-package: cn.edu.handler
'''

风中的雪糕 | 园豆:418 (菜鸟二级) | 2020-01-21 21:32

这种方法不行,在idea中可以运行的,没有报错。Java -jar 就报错

支持(0) 反对(0) pakl | 园豆:50 (初学一级) | 2020-01-21 21:36

@pakl: Java -jar 你要启动spring啊...导入spring的包啊

支持(0) 反对(0) 风中的雪糕 | 园豆:418 (菜鸟二级) | 2020-02-08 13:37
0

你这个应该不是 mybatis-plus 的问题,而是 打包方法的问题,百度一下吧

15klli | 园豆:21 (初学一级) | 2020-03-30 16:42
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册