Browse Source

返回Map自动下划线转驼峰

configuration需配置ObjectWrapperFactory,参考
MybatisPlusConfigMapUnderline2Camel
yuxiaobin 7 years ago
parent
commit
c541085859

+ 2 - 1
build.gradle

@@ -33,7 +33,8 @@ ext {
             "spring-context-support":"org.springframework:spring-context-support:${springVersion}",
             "spring-jdbc":"org.springframework:spring-jdbc:${springVersion}",
             "spring-tx":"org.springframework:spring-tx:${springVersion}",
-            "druid":"com.alibaba:druid:1.0.29"
+            "druid":"com.alibaba:druid:1.0.29",
+            "fastjson":"com.alibaba:fastjson:1.2.37"
     ]
 }
 

+ 1 - 0
mybatis-plus-core/build.gradle

@@ -29,4 +29,5 @@ dependencies {
     testCompile rootProject.ext.dependencies["lombok"]
     testCompile rootProject.ext.dependencies["hikaricp"]
     testCompile rootProject.ext.dependencies["druid"]
+    testCompile rootProject.ext.dependencies["fastjson"]
 }

+ 30 - 0
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/MybatisMapWrapperFactory.java

@@ -0,0 +1,30 @@
+package com.baomidou.mybatisplus;
+
+import java.util.Map;
+
+import org.apache.ibatis.reflection.MetaObject;
+import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
+import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
+
+import com.baomidou.mybatisplus.mapper.MybatisMapWrapper;
+
+/**
+ * <p>
+ *   开启返回map结果集的下划线转驼峰
+ * </p>
+ *
+ * @author yuxiaobin
+ * @date 2017/12/19
+ */
+public class MybatisMapWrapperFactory implements ObjectWrapperFactory {
+
+    @Override
+    public boolean hasWrapperFor(Object object) {
+        return object != null && object instanceof Map;
+    }
+
+    @Override
+    public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
+        return new MybatisMapWrapper(metaObject, (Map) object);
+    }
+}

+ 32 - 0
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/mapper/MybatisMapWrapper.java

@@ -0,0 +1,32 @@
+package com.baomidou.mybatisplus.mapper;
+
+import java.util.Map;
+
+import org.apache.ibatis.reflection.MetaObject;
+import org.apache.ibatis.reflection.wrapper.MapWrapper;
+
+import com.baomidou.mybatisplus.toolkit.StringUtils;
+
+/**
+ * <p>
+ *     返回Map结果集,下划线转驼峰
+ * </p>
+ *
+ * @author yuxiaobin
+ * @date 2017/12/19
+ */
+public class MybatisMapWrapper extends MapWrapper {
+    public MybatisMapWrapper(MetaObject metaObject, Map<String, Object> map) {
+        super(metaObject, map);
+    }
+
+    @Override
+    public String findProperty(String name, boolean useCamelCaseMapping) {
+        if (useCamelCaseMapping
+                && ((name.charAt(0) >= 'A' && name.charAt(0) <= 'Z')
+                || name.contains("_"))) {
+            return StringUtils.underlineToCamel(name);
+        }
+        return name;
+    }
+}

+ 104 - 0
mybatis-plus-core/src/test/java/com/baomidou/mybatisplus/test/h2/H2MapUnderline2CamelTest.java

@@ -0,0 +1,104 @@
+package com.baomidou.mybatisplus.test.h2;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.Map;
+
+import javax.sql.DataSource;
+
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
+
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.mapper.EntityWrapper;
+import com.baomidou.mybatisplus.test.h2.base.H2Test;
+import com.baomidou.mybatisplus.test.h2.config.DBConfig;
+import com.baomidou.mybatisplus.test.h2.config.MybatisPlusConfigMapUnderline2Camel;
+import com.baomidou.mybatisplus.test.h2.entity.persistent.H2User;
+import com.baomidou.mybatisplus.test.h2.service.IH2UserService;
+
+/**
+ * <p>
+ * 测试返回Map结果集,下划线自动转驼峰
+ * </p>
+ *
+ * @author yuxiaobin
+ * @date 2017/12/19
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = {DBConfig.class, MybatisPlusConfigMapUnderline2Camel.class})
+public class H2MapUnderline2CamelTest extends H2Test {
+
+    @Autowired
+    IH2UserService userService;
+
+    @BeforeClass
+    public static void init() throws SQLException, IOException {
+        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
+        context.register(DBConfig.class);
+        context.refresh();
+        DataSource ds = (DataSource) context.getBean("dataSource");
+        try (Connection conn = ds.getConnection()) {
+            initData(conn);
+        }
+    }
+
+    @Test
+    public void testMapUnderline2Camel() {
+        List<Map<String, Object>> list = userService.selectMaps(new EntityWrapper<H2User>());
+        for (Map<String, Object> map : list) {
+            System.out.println(JSONObject.toJSON(map));
+        }
+    }
+
+    @Test
+    public void testMapUnderline2CamelMyMethods() {
+        List<Map> list = userService.mySelectMaps();
+        for (Map map : list) {
+            System.out.println(JSONObject.toJSON(map));
+            Assert.assertNotNull("test_id should be auto converted to testId", map.get("testId"));
+            Assert.assertNotNull("test_type should be auto converted to testType", map.get("testType"));
+        }
+    }
+
+    @Test
+    public void testSelectSql4SelectMaps() {
+        EntityWrapper<H2User> ew = new EntityWrapper<>();
+        ew.setSqlSelect("test_id, test_type");
+        List<Map<String, Object>> list = userService.selectMaps(ew);
+        for (Map<String, Object> map : list) {
+            System.out.println(JSONObject.toJSON(map));
+            Assert.assertNotNull("test_id should be convert to testId", map.get("testId"));
+            Assert.assertNotNull("test_type should be convert to testType", map.get("testType"));
+        }
+    }
+
+    @Test
+    public void testSelectSqlNotMapping() {
+        EntityWrapper<H2User> ew = new EntityWrapper<>();
+        ew.setSqlSelect("test_id, test_type");
+        List<H2User> list = userService.selectList(ew);
+        for (H2User u : list) {
+            System.out.println(JSONObject.toJSON(u));
+            Assert.assertNull("test_id is not null, but should not mapping to id", u.getId());
+            Assert.assertNotNull("test_type should be convert to testType", u.getTestType());
+        }
+    }
+
+    @Test
+    public void testMpSelect() {
+        List<H2User> list = userService.selectList(new EntityWrapper<H2User>());
+        for (H2User u : list) {
+            Assert.assertNotNull("id should not be null", u.getId());
+            Assert.assertNotNull("test_type should not be null", u.getTestType());
+        }
+    }
+}

+ 71 - 0
mybatis-plus-core/src/test/java/com/baomidou/mybatisplus/test/h2/config/MybatisPlusConfigMapUnderline2Camel.java

@@ -0,0 +1,71 @@
+package com.baomidou.mybatisplus.test.h2.config;
+
+import javax.sql.DataSource;
+
+import org.apache.ibatis.plugin.Interceptor;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.apache.ibatis.type.JdbcType;
+import org.mybatis.spring.annotation.MapperScan;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.io.ResourceLoader;
+
+import com.baomidou.mybatisplus.MybatisMapWrapperFactory;
+import com.baomidou.mybatisplus.MybatisConfiguration;
+import com.baomidou.mybatisplus.entity.GlobalConfiguration;
+import com.baomidou.mybatisplus.mapper.LogicSqlInjector;
+import com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor;
+import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
+import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
+import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
+import com.baomidou.mybatisplus.test.h2.H2MetaObjectHandler;
+
+/**
+ * <p>
+ * Mybatis Plus Config
+ * </p>
+ *
+ * @author Caratacus
+ * @date 2017/4/1
+ */
+@Configuration
+@MapperScan("com.baomidou.mybatisplus.test.h2.entity.mapper")
+@ComponentScan("com.baomidou.mybatisplus.test.h2.service")
+public class MybatisPlusConfigMapUnderline2Camel {
+
+    @Bean("mybatisSqlSession")
+    public SqlSessionFactory sqlSessionFactory(DataSource dataSource, ResourceLoader resourceLoader, GlobalConfiguration globalConfiguration) throws Exception {
+        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
+        sqlSessionFactory.setDataSource(dataSource);
+//        sqlSessionFactory.setConfigLocation(resourceLoader.getResource("classpath:mybatis-config.xml"));
+        sqlSessionFactory.setTypeAliasesPackage("com.baomidou.mybatisplus.test.h2.entity.persistent");
+        MybatisConfiguration configuration = new MybatisConfiguration();
+//        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
+//        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
+        configuration.setJdbcTypeForNull(JdbcType.NULL);
+        configuration.setMapUnderscoreToCamelCase(true);
+        //注册Map 下划线转驼峰
+        configuration.setObjectWrapperFactory(new MybatisMapWrapperFactory());
+        sqlSessionFactory.setConfiguration(configuration);
+        PaginationInterceptor pagination = new PaginationInterceptor();
+        OptimisticLockerInterceptor optLock = new OptimisticLockerInterceptor();
+        sqlSessionFactory.setPlugins(new Interceptor[]{
+                pagination,
+                optLock,
+                new PerformanceInterceptor()
+        });
+        globalConfiguration.setMetaObjectHandler(new H2MetaObjectHandler());
+        sqlSessionFactory.setGlobalConfig(globalConfiguration);
+        return sqlSessionFactory.getObject();
+    }
+
+    @Bean
+    public GlobalConfiguration globalConfiguration() {
+        GlobalConfiguration conf = new GlobalConfiguration(new LogicSqlInjector());
+        conf.setLogicDeleteValue("-1");
+        conf.setLogicNotDeleteValue("1");
+        conf.setIdType(2);
+        return conf;
+    }
+}

+ 3 - 0
mybatis-plus-core/src/test/java/com/baomidou/mybatisplus/test/h2/entity/mapper/H2UserMapper.java

@@ -79,4 +79,7 @@ public interface H2UserMapper extends SuperMapper<H2User> {
             " where age>#{ageFrom} and age<#{ageTo} " +
             ") a")
     int selectCountWithParamInSelectItems(Map<String, Object> param);
+
+    @Select("select * from h2user")
+    List<Map> mySelectMaps();
 }

+ 2 - 0
mybatis-plus-core/src/test/java/com/baomidou/mybatisplus/test/h2/service/IH2UserService.java

@@ -45,4 +45,6 @@ public interface IH2UserService extends IService<H2User> {
     Page<H2User> queryWithParamInSelectStatememt4Page(Map<String, Object> param, Page<H2User> page);
 
     int selectCountWithParamInSelectItems(Map<String, Object> param);
+
+    List<Map> mySelectMaps();
 }

+ 5 - 0
mybatis-plus-core/src/test/java/com/baomidou/mybatisplus/test/h2/service/impl/H2UserServiceImpl.java

@@ -83,4 +83,9 @@ public class H2UserServiceImpl extends ServiceImpl<H2UserMapper, H2User> impleme
     public int selectCountWithParamInSelectItems(Map<String, Object> param) {
         return userMapper.selectCountWithParamInSelectItems(param);
     }
+
+    @Override
+    public List<Map> mySelectMaps() {
+        return userMapper.mySelectMaps();
+    }
 }