Browse Source

EnumTypeHandler 更名为 MybatisEnumTypeHandler,移除 EnumAnnotationTypeHandler

miemie 6 years ago
parent
commit
ef89782124

+ 11 - 12
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/handlers/EnumTypeHandler.java

@@ -20,7 +20,6 @@ import com.baomidou.mybatisplus.core.enums.IEnum;
 import com.baomidou.mybatisplus.core.toolkit.EnumUtils;
 import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
 import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
-
 import org.apache.ibatis.logging.Log;
 import org.apache.ibatis.logging.LogFactory;
 import org.apache.ibatis.type.BaseTypeHandler;
@@ -44,16 +43,17 @@ import java.util.concurrent.ConcurrentHashMap;
  * @author hubin
  * @since 2017-10-11
  */
+@Deprecated
 public class EnumTypeHandler<E extends Enum<?>> extends BaseTypeHandler<Enum<?>> {
-    
+
     private static final Log LOGGER = LogFactory.getLog(EnumTypeHandler.class);
-    
+
     private static final Map<Class<?>, Method> TABLE_METHOD_OF_ENUM_TYPES = new ConcurrentHashMap<>();
-    
+
     private final Class<E> type;
-    
+
     private final Method method;
-    
+
     public EnumTypeHandler(Class<E> type) {
         if (type == null) {
             throw new IllegalArgumentException("Type argument cannot be null");
@@ -72,7 +72,7 @@ public class EnumTypeHandler<E extends Enum<?>> extends BaseTypeHandler<Enum<?>>
             });
         }
     }
-    
+
     @SuppressWarnings("Duplicates")
     @Override
     public void setNonNullParameter(PreparedStatement ps, int i, Enum<?> parameter, JdbcType jdbcType)
@@ -91,7 +91,7 @@ public class EnumTypeHandler<E extends Enum<?>> extends BaseTypeHandler<Enum<?>>
             throw ExceptionUtils.mpe("Error: NoSuchMethod in %s.  Cause:", e, this.type.getName());
         }
     }
-    
+
     @Override
     public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
         if (null == rs.getObject(columnName) && rs.wasNull()) {
@@ -99,7 +99,7 @@ public class EnumTypeHandler<E extends Enum<?>> extends BaseTypeHandler<Enum<?>>
         }
         return EnumUtils.valueOf(this.type, rs.getObject(columnName), this.method);
     }
-    
+
     @Override
     public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
         if (null == rs.getObject(columnIndex) && rs.wasNull()) {
@@ -107,7 +107,7 @@ public class EnumTypeHandler<E extends Enum<?>> extends BaseTypeHandler<Enum<?>>
         }
         return EnumUtils.valueOf(this.type, rs.getObject(columnIndex), this.method);
     }
-    
+
     @Override
     public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
         if (null == cs.getObject(columnIndex) && cs.wasNull()) {
@@ -115,9 +115,8 @@ public class EnumTypeHandler<E extends Enum<?>> extends BaseTypeHandler<Enum<?>>
         }
         return EnumUtils.valueOf(this.type, cs.getObject(columnIndex), this.method);
     }
-    
+
     public static Optional<Field> dealEnumType(Class<?> clazz) {
         return clazz.isEnum() ? Arrays.stream(clazz.getDeclaredFields()).filter(field -> field.isAnnotationPresent(EnumValue.class)).findFirst() : Optional.empty();
     }
-    
 }

+ 37 - 29
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/handlers/EnumAnnotationTypeHandler.java → mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/handlers/MybatisEnumTypeHandler.java

@@ -16,10 +16,10 @@
 package com.baomidou.mybatisplus.extension.handlers;
 
 import com.baomidou.mybatisplus.annotation.EnumValue;
+import com.baomidou.mybatisplus.core.enums.IEnum;
 import com.baomidou.mybatisplus.core.toolkit.EnumUtils;
 import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
 import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
-
 import org.apache.ibatis.logging.Log;
 import org.apache.ibatis.logging.LogFactory;
 import org.apache.ibatis.type.BaseTypeHandler;
@@ -38,16 +38,14 @@ import java.util.Optional;
 import java.util.concurrent.ConcurrentHashMap;
 
 /**
- * EnumValue 注解自定义枚举属性转换器
+ * 自定义枚举属性转换器
  *
- * @author yuxiaobin
- * @date 2018-08-30
- * @deprecated  3.0.8 {@link com.baomidou.mybatisplus.extension.handlers.EnumTypeHandler}
+ * @author hubin
+ * @since 2017-10-11
  */
-@Deprecated
-public class EnumAnnotationTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {
-    
-    private static final Log LOGGER = LogFactory.getLog(EnumAnnotationTypeHandler.class);
+public class MybatisEnumTypeHandler<E extends Enum<?>> extends BaseTypeHandler<Enum<?>> {
+
+    private static final Log LOGGER = LogFactory.getLog(MybatisEnumTypeHandler.class);
     
     private static final Map<Class<?>, Method> TABLE_METHOD_OF_ENUM_TYPES = new ConcurrentHashMap<>();
     
@@ -55,59 +53,69 @@ public class EnumAnnotationTypeHandler<E extends Enum<E>> extends BaseTypeHandle
     
     private final Method method;
 
-    public EnumAnnotationTypeHandler(Class<E> type) {
+    public MybatisEnumTypeHandler(Class<E> type) {
         if (type == null) {
             throw new IllegalArgumentException("Type argument cannot be null");
         }
         this.type = type;
-        this.method = TABLE_METHOD_OF_ENUM_TYPES.computeIfAbsent(type, k-> {
-            Field field = dealEnumType(this.type).orElseThrow(() -> new IllegalArgumentException(String.format("Could not find @EnumValue in Class: %s.", type.getName())));
-            return ReflectionKit.getMethod(this.type, field);
-        });
+        if (IEnum.class.isAssignableFrom(type)) {
+            try {
+                this.method = type.getMethod("getValue");
+            } catch (NoSuchMethodException e) {
+                throw new IllegalArgumentException(String.format("NoSuchMethod getValue() in Class: %s.", type.getName()));
+            }
+        } else {
+            this.method = TABLE_METHOD_OF_ENUM_TYPES.computeIfAbsent(type, k -> {
+                Field field = dealEnumType(this.type).orElseThrow(() -> new IllegalArgumentException(String.format("Could not find @EnumValue in Class: %s.", type.getName())));
+                return ReflectionKit.getMethod(this.type, field);
+            });
+        }
     }
-
+    
     @SuppressWarnings("Duplicates")
     @Override
-    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
+    public void setNonNullParameter(PreparedStatement ps, int i, Enum<?> parameter, JdbcType jdbcType)
+        throws SQLException {
         try {
-            method.setAccessible(true);
+            this.method.setAccessible(true);
             if (jdbcType == null) {
-                ps.setObject(i, method.invoke(parameter));
+                ps.setObject(i, this.method.invoke(parameter));
             } else {
                 // see r3589
-                ps.setObject(i, method.invoke(parameter), jdbcType.TYPE_CODE);
+                ps.setObject(i, this.method.invoke(parameter), jdbcType.TYPE_CODE);
             }
         } catch (IllegalAccessException e) {
             LOGGER.error("unrecognized jdbcType, failed to set StringValue for type=" + parameter);
         } catch (InvocationTargetException e) {
-            throw ExceptionUtils.mpe("Error: NoSuchMethod in %s.  Cause:", e, type.getName());
+            throw ExceptionUtils.mpe("Error: NoSuchMethod in %s.  Cause:", e, this.type.getName());
         }
     }
 
     @Override
     public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
-        return getEnumResult(rs.getObject(columnName));
-    }
-
-    private E getEnumResult(Object s) {
-        if (s == null) {
+        if (null == rs.getObject(columnName) && rs.wasNull()) {
             return null;
         }
-        return EnumUtils.valueOf(type, s, method);
+        return EnumUtils.valueOf(this.type, rs.getObject(columnName), this.method);
     }
 
     @Override
     public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
-        return getEnumResult(rs.getObject(columnIndex));
+        if (null == rs.getObject(columnIndex) && rs.wasNull()) {
+            return null;
+        }
+        return EnumUtils.valueOf(this.type, rs.getObject(columnIndex), this.method);
     }
 
     @Override
     public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
-        return getEnumResult(cs.getObject(columnIndex));
+        if (null == cs.getObject(columnIndex) && cs.wasNull()) {
+            return null;
+        }
+        return EnumUtils.valueOf(this.type, cs.getObject(columnIndex), this.method);
     }
 
     public static Optional<Field> dealEnumType(Class<?> clazz) {
         return clazz.isEnum() ? Arrays.stream(clazz.getDeclaredFields()).filter(field -> field.isAnnotationPresent(EnumValue.class)).findFirst() : Optional.empty();
     }
-    
 }

+ 3 - 3
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/spring/MybatisSqlSessionFactoryBean.java

@@ -27,7 +27,7 @@ import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
 import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
 import com.baomidou.mybatisplus.core.toolkit.StringPool;
 import com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory;
-import com.baomidou.mybatisplus.extension.handlers.EnumTypeHandler;
+import com.baomidou.mybatisplus.extension.handlers.MybatisEnumTypeHandler;
 import com.baomidou.mybatisplus.extension.toolkit.AopUtils;
 import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
 import com.baomidou.mybatisplus.extension.toolkit.PackageHelper;
@@ -517,8 +517,8 @@ public class MybatisSqlSessionFactoryBean implements FactoryBean<SqlSessionFacto
             TypeHandlerRegistry typeHandlerRegistry = targetConfiguration.getTypeHandlerRegistry();
             classes.stream()
                 .filter(Class::isEnum)
-                .filter(cls -> IEnum.class.isAssignableFrom(cls) || EnumTypeHandler.dealEnumType(cls).isPresent())
-                .forEach(cls -> typeHandlerRegistry.register(cls, EnumTypeHandler.class));
+                .filter(cls -> IEnum.class.isAssignableFrom(cls) || MybatisEnumTypeHandler.dealEnumType(cls).isPresent())
+                .forEach(cls -> typeHandlerRegistry.register(cls, MybatisEnumTypeHandler.class));
         }
 
         Optional.ofNullable(this.objectFactory).ifPresent(targetConfiguration::setObjectFactory);

+ 0 - 93
mybatis-plus-extension/src/test/java/com/baomidou/mybatisplus/extension/handlers/EnumAnnotationTypeHandlerTest.java

@@ -1,93 +0,0 @@
-/*
- * Copyright (c) 2011-2019, hubin (jobob@qq.com).
- * <p>
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- * <p>
- * https://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.baomidou.mybatisplus.extension.handlers;
-
-import com.baomidou.mybatisplus.annotation.EnumValue;
-
-import org.apache.ibatis.type.JdbcType;
-import org.apache.ibatis.type.TypeHandler;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-@ExtendWith(MockitoExtension.class)
-public class EnumAnnotationTypeHandlerTest extends BaseTypeHandlerTest {
-
-    private static final TypeHandler<SexEnum> HANDLER = new EnumAnnotationTypeHandler<>(SexEnum.class);
-
-    @Getter
-    @AllArgsConstructor
-    enum SexEnum {
-        MAN(1, "男人"), WO_MAN(2, "女人");
-        @EnumValue
-        Integer code;
-        String desc;
-    }
-
-    @Test
-    @Override
-    public void setParameter() throws Exception {
-        HANDLER.setParameter(preparedStatement, 1, null, JdbcType.INTEGER);
-        verify(preparedStatement).setNull(1, JdbcType.INTEGER.TYPE_CODE);
-        HANDLER.setParameter(preparedStatement, 2, SexEnum.MAN, null);
-        verify(preparedStatement).setObject(2, 1);
-        HANDLER.setParameter(preparedStatement, 3, SexEnum.WO_MAN, null);
-        verify(preparedStatement).setObject(3, 2);
-    }
-
-    @Test
-    @Override
-    public void getResultFromResultSetByColumnName() throws Exception {
-        when(resultSet.getObject("column")).thenReturn(null);
-        assertNull(HANDLER.getResult(resultSet, "column"));
-        when(resultSet.getObject("column")).thenReturn(1);
-        assertEquals(SexEnum.MAN, HANDLER.getResult(resultSet, "column"));
-        when(resultSet.getObject("column")).thenReturn(2);
-        assertEquals(SexEnum.WO_MAN, HANDLER.getResult(resultSet, "column"));
-    }
-
-    @Test
-    @Override
-    public void getResultFromResultSetByColumnIndex() throws Exception {
-        when(resultSet.getObject(1)).thenReturn(1);
-        assertEquals(SexEnum.MAN, HANDLER.getResult(resultSet, 1));
-        when(resultSet.getObject(2)).thenReturn(2);
-        assertEquals(SexEnum.WO_MAN, HANDLER.getResult(resultSet, 2));
-        when(resultSet.getObject(3)).thenReturn(null);
-        assertNull(HANDLER.getResult(resultSet, 3));
-    }
-
-    @Test
-    @Override
-    public void getResultFromCallableStatement() throws Exception {
-        when(callableStatement.getObject(1)).thenReturn(1);
-        assertEquals(SexEnum.MAN, HANDLER.getResult(callableStatement, 1));
-        when(callableStatement.getObject(2)).thenReturn(2);
-        assertEquals(SexEnum.WO_MAN, HANDLER.getResult(callableStatement, 2));
-        when(callableStatement.getObject(3)).thenReturn(null);
-        assertNull(HANDLER.getResult(callableStatement, 3));
-
-    }
-
-}

+ 7 - 9
mybatis-plus-extension/src/test/java/com/baomidou/mybatisplus/extension/handlers/EnumTypeHandlerTest.java → mybatis-plus-extension/src/test/java/com/baomidou/mybatisplus/extension/handlers/MybatisEnumTypeHandlerTest.java

@@ -17,26 +17,24 @@ package com.baomidou.mybatisplus.extension.handlers;
 
 import com.baomidou.mybatisplus.annotation.EnumValue;
 import com.baomidou.mybatisplus.core.enums.IEnum;
-
+import lombok.AllArgsConstructor;
+import lombok.Getter;
 import org.apache.ibatis.type.JdbcType;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
 import org.mockito.junit.jupiter.MockitoExtension;
 
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 @ExtendWith(MockitoExtension.class)
-public class EnumTypeHandlerTest extends BaseTypeHandlerTest {
-    
-    private static final EnumTypeHandler<SexEnum> SEX_ENUM_ENUM_TYPE_HANDLER = new EnumTypeHandler<>(SexEnum.class);
-    
-    private static final EnumTypeHandler<GradeEnum> GRADE_ENUM_ENUM_TYPE_HANDLER = new EnumTypeHandler<>(GradeEnum.class);
+public class MybatisEnumTypeHandlerTest extends BaseTypeHandlerTest {
+
+    private static final MybatisEnumTypeHandler<SexEnum> SEX_ENUM_ENUM_TYPE_HANDLER = new MybatisEnumTypeHandler<>(SexEnum.class);
+
+    private static final MybatisEnumTypeHandler<GradeEnum> GRADE_ENUM_ENUM_TYPE_HANDLER = new MybatisEnumTypeHandler<>(GradeEnum.class);
     
     @Getter
     @AllArgsConstructor

+ 3 - 4
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/MybatisTest.java

@@ -19,11 +19,10 @@ import com.alibaba.druid.pool.DruidDataSource;
 import com.baomidou.mybatisplus.annotation.DbType;
 import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
-import com.baomidou.mybatisplus.extension.handlers.EnumTypeHandler;
+import com.baomidou.mybatisplus.extension.handlers.MybatisEnumTypeHandler;
+import com.baomidou.mybatisplus.test.h2.entity.H2User;
 import com.baomidou.mybatisplus.test.h2.enums.AgeEnum;
 import com.baomidou.mybatisplus.test.h2.mapper.H2UserMapper;
-import com.baomidou.mybatisplus.test.h2.entity.H2User;
-
 import org.apache.ibatis.io.Resources;
 import org.apache.ibatis.jdbc.ScriptRunner;
 import org.apache.ibatis.session.Configuration;
@@ -68,7 +67,7 @@ class MybatisTest {
          *  如果是将defaultEnumTypeHandler设置成MP的处理器,
          *  请自行注册处理非MP枚举处理类的原生枚举类型
          */
-        typeHandlerRegistry.register(AgeEnum.class, EnumTypeHandler.class);     //这里我举起了个栗子
+        typeHandlerRegistry.register(AgeEnum.class, MybatisEnumTypeHandler.class);     //这里我举起了个栗子
         Connection connection = dataSource.getConnection();
         ScriptRunner scriptRunner = new ScriptRunner(connection);
         scriptRunner.runScript(Resources.getResourceAsReader("h2/user.ddl.sql"));

+ 2 - 1
mybatis-plus/src/test/resources/mybatis-config.xml

@@ -5,7 +5,8 @@
 <configuration>
 
     <settings>
-        <setting name="defaultEnumTypeHandler" value="com.baomidou.mybatisplus.extension.handlers.EnumTypeHandler"/>
+        <setting name="defaultEnumTypeHandler"
+                 value="com.baomidou.mybatisplus.extension.handlers.MybatisEnumTypeHandler"/>
     </settings>
 
     <mappers>