Browse Source

调整新增跨 xml resultMap 引用测试用例

= 8 years ago
parent
commit
120d7579c9

+ 1 - 1
src/main/java/com/baomidou/mybatisplus/generator/AutoGenerator.java

@@ -184,7 +184,7 @@ public class AutoGenerator {
                     if (field.getPropertyType().equalsIgnoreCase("boolean")) {
                         if (field.getPropertyName().contains("is")) {
                             field.setPropertyName(config.getStrategyConfig(),
-                                    field.getPropertyName().substring(0, 3).toLowerCase().substring(2));
+                                    StringUtils.removePrefixAfterPrefixToLower(field.getPropertyName(), 2));
                         }
                     }
                 }

+ 5 - 28
src/main/java/com/baomidou/mybatisplus/mapper/MetaObjectHandler.java

@@ -62,7 +62,7 @@ public abstract class MetaObjectHandler {
      * @param metaObject meta object parameter
      */
     public MetaObjectHandler setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject) {
-        if(metaObject.hasGetter(fieldName)) {
+        if (metaObject.hasGetter(fieldName)) {
             metaObject.setValue(fieldName, fieldVal);
         } else if (metaObject.hasGetter(META_OBJ_PREFIX + "." + fieldName)) {
             metaObject.setValue(META_OBJ_PREFIX + "." + fieldName, fieldVal);
@@ -83,35 +83,12 @@ public abstract class MetaObjectHandler {
      * @return
      */
     public Object getFieldValByName(String fieldName, MetaObject metaObject) {
-        String[] fieldNames = metaObject.getGetterNames();
-        boolean containsEt = false;
-        for (String name : fieldNames) {
-            if (META_OBJ_PREFIX.equals(name)) {
-                containsEt = true;
-                break;
-            }
-        }
-        if (containsEt) {
-            return metaObject.getValue(META_OBJ_PREFIX + "." + fieldName);
-        } else {
-            return metaObject.getValue(fieldName);
-        }
-    }
-
-    /**
-     * <p>
-     * 是否存在属性,判断 et 别名方法
-     * </p>
-     *
-     * @param fieldName  java bean property name
-     * @param metaObject parameter wrapper
-     * @return
-     */
-    public boolean hasGetter(String fieldName, MetaObject metaObject) {
         if (metaObject.hasGetter(fieldName)) {
-            return true;
+            return metaObject.getValue(fieldName);
+        } else if (metaObject.hasGetter(META_OBJ_PREFIX + "." + fieldName)) {
+            return metaObject.getValue(META_OBJ_PREFIX + "." + fieldName);
         }
-        return metaObject.hasGetter(META_OBJ_PREFIX + "." + fieldName);
+        return null;
     }
 
     /**

+ 46 - 4
src/main/java/com/baomidou/mybatisplus/toolkit/StringUtils.java

@@ -620,11 +620,53 @@ public class StringUtils {
 
     /**
      * <p>
-     * 驼峰转连字符
+     * 第一个首字母小写,之后字符大小写的不变<br>
+     * StringUtils.firstCharToLower( "UserService" )     = userService
+     * StringUtils.firstCharToLower( "UserServiceImpl" ) = userServiceImpl
+     * </p>
+     *
+     * @param rawString 需要处理的字符串
+     * @return
+     */
+    public static String firstCharToLower(String rawString) {
+        return prefixToLower(rawString, 1);
+    }
+
+    /**
+     * <p>
+     * 前n个首字母小写,之后字符大小写的不变
+     * </p>
+     *
+     * @param rawString 需要处理的字符串
+     * @param index     多少个字符(从左至右)
+     * @return
+     */
+    public static String prefixToLower(String rawString, int index) {
+        String beforeChar = rawString.substring(0, index).toLowerCase();
+        String afterChar = rawString.substring(index, rawString.length());
+        return beforeChar + afterChar;
+    }
+
+    /**
+     * <p>
+     * 删除字符前缀之后,首字母小写,之后字符大小写的不变<br>
+     * StringUtils.removePrefixAfterPrefixToLower( "isUser", 2 )     = user
+     * StringUtils.removePrefixAfterPrefixToLower( "isUserInfo", 2 ) = userInfo
+     * </p>
+     *
+     * @param rawString 需要处理的字符串
+     * @param index     删除多少个字符(从左至右)
+     * @return
+     */
+    public static String removePrefixAfterPrefixToLower(String rawString, int index) {
+        return prefixToLower(rawString.substring(index, rawString.length()), 1);
+    }
+
+    /**
+     * <p>
+     * 驼峰转连字符<br>
+     * StringUtils.camelToHyphen( "managerAdminUserService" ) = manager-admin-user-service
      * </p>
-     * <pre>
-     *     StringUtils.camelToHyphen( "managerAdminUserService" ) = manager-admin-user-service
-     * </pre>
      *
      * @param input
      * @return 以'-'分隔

+ 38 - 0
src/test/java/com/baomidou/mybatisplus/test/StringUtilsTest.java

@@ -0,0 +1,38 @@
+/**
+ * Copyright (c) 2011-2020, 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>
+ * http://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.test;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.baomidou.mybatisplus.toolkit.StringUtils;
+
+/**
+ * <p>
+ * 字符串工具类测试
+ * </p>
+ *
+ * @author hubin
+ * @date 2017-06-27
+ */
+public class StringUtilsTest {
+
+    @Test
+    public void removePrefixAfterPrefixToLower(){
+        Assert.assertEquals("user", StringUtils.removePrefixAfterPrefixToLower( "isUser", 2 ));
+        Assert.assertEquals("userInfo", StringUtils.removePrefixAfterPrefixToLower( "isUserInfo", 2 ));
+    }
+}

+ 0 - 79
src/test/java/com/baomidou/mybatisplus/test/h2/H2FillFieldTest.java

@@ -1,79 +0,0 @@
-package com.baomidou.mybatisplus.test.h2;
-
-import java.io.IOException;
-import java.sql.Connection;
-import java.sql.SQLException;
-import java.sql.Statement;
-
-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.context.ApplicationContext;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import com.baomidou.mybatisplus.test.h2.config.DBConfig;
-import com.baomidou.mybatisplus.test.h2.config.MybatisPlusNoOptLockConfig;
-import com.baomidou.mybatisplus.test.h2.entity.mapper.H2UserFillMapper;
-import com.baomidou.mybatisplus.test.h2.entity.persistent.H2UserFill;
-
-/**
- * <p>
- * </p>
- *
- * @author yuxiaobin
- * @date 2017/5/31
- */
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = {DBConfig.class, MybatisPlusNoOptLockConfig.class})
-public class H2FillFieldTest extends H2Test {
-
-    @Autowired
-    H2UserFillMapper fillMapper;
-
-    @BeforeClass
-    public static void initDB() throws SQLException, IOException {
-        @SuppressWarnings("resource")
-        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:h2/spring-test-h2.xml");
-        DataSource ds = (DataSource) context.getBean("dataSource");
-        try (Connection conn = ds.getConnection()) {
-            String createTableSql = readFile("user.ddl.sql");
-            Statement stmt = conn.createStatement();
-            stmt.execute(createTableSql);
-            stmt.execute("truncate table h2user");
-            executeSql(stmt, "user.insert.sql");
-            conn.commit();
-        }
-    }
-
-
-    @Test
-    public void testFill() {
-        H2UserFill u = new H2UserFill();
-        u.setName("ignoreTest");
-        u.setTestType(1);
-        u.setDesc("ignoreDesc");
-        Assert.assertEquals(1, fillMapper.insert(u).intValue());
-
-        Long id = u.getId();
-        Assert.assertNotNull(id);
-
-        H2UserFill dbUser = fillMapper.selectById(id);
-        Assert.assertNull(dbUser.getTestType());
-        Assert.assertNotNull(dbUser.getDesc());
-
-        dbUser.setTestType(2);
-        dbUser.setDesc("ignoreDesc2");
-        Assert.assertEquals(1, fillMapper.updateById(dbUser).intValue());
-
-        dbUser = fillMapper.selectById(id);
-        Assert.assertEquals("ignoreDesc", dbUser.getDesc());
-        Assert.assertEquals(2, dbUser.getTestType().intValue());
-    }
-
-}

+ 2 - 2
src/test/java/com/baomidou/mybatisplus/test/h2/H2MetaObjectHandler.java

@@ -40,10 +40,10 @@ public class H2MetaObjectHandler extends MetaObjectHandler {
         System.out.println("*************************");
 
         // 测试下划线
-        Object testType = getFieldValByName("testType", metaObject);
+        Object testType = this.getFieldValByName("testType", metaObject);
         System.out.println("testType=" + testType);
         if (testType == null) {
-            setFieldValByName("testType", 3, metaObject);
+            this.setFieldValByName("testType", 3, metaObject);
         }
     }
 

+ 1 - 2
src/test/java/com/baomidou/mybatisplus/test/h2/H2MetaObjectHandlerTest.java

@@ -80,7 +80,7 @@ public class H2MetaObjectHandlerTest extends H2Test {
         Date lastUpdatedDt = userDB.getLastUpdatedDt();
         System.out.println("after update: testDate=" + lastUpdatedDt);
         String versionDateStr = sdf.format(lastUpdatedDt);
-        //MyMetaObjectHandler.updateFill() : set 
+        //MyMetaObjectHandler.updateFill() : set
         Assert.assertEquals(sdf.format(new Date()), versionDateStr);
     }
 
@@ -110,7 +110,6 @@ public class H2MetaObjectHandlerTest extends H2Test {
         Assert.assertNotNull(dbUser);
         Assert.assertEquals("updateMy", dbUser.getName());
         Assert.assertEquals(1, user.getVersion().intValue());
-
     }
 
 }

+ 2 - 0
src/test/java/com/baomidou/mybatisplus/test/h2/config/MybatisPlusConfig.java

@@ -18,6 +18,7 @@ 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>
@@ -48,6 +49,7 @@ public class MybatisPlusConfig {
                 optLock,
                 new PerformanceInterceptor()
         });
+        globalConfiguration.setMetaObjectHandler(new H2MetaObjectHandler());
         sqlSessionFactory.setGlobalConfig(globalConfiguration);
         return sqlSessionFactory.getObject();
     }

+ 0 - 15
src/test/java/com/baomidou/mybatisplus/test/h2/entity/mapper/H2UserFillMapper.java

@@ -1,15 +0,0 @@
-package com.baomidou.mybatisplus.test.h2.entity.mapper;
-
-import com.baomidou.mybatisplus.mapper.BaseMapper;
-import com.baomidou.mybatisplus.test.h2.entity.persistent.H2UserFill;
-
-/**
- * <p>
- * </p>
- *
- * @author yuxiaobin
- * @date 2017/6/28
- */
-public interface H2UserFillMapper extends BaseMapper<H2UserFill> {
-
-}

+ 0 - 45
src/test/java/com/baomidou/mybatisplus/test/h2/entity/persistent/H2UserFill.java

@@ -1,45 +0,0 @@
-package com.baomidou.mybatisplus.test.h2.entity.persistent;
-
-import java.math.BigDecimal;
-
-import com.baomidou.mybatisplus.annotations.TableField;
-import com.baomidou.mybatisplus.annotations.TableName;
-import com.baomidou.mybatisplus.annotations.Version;
-import com.baomidou.mybatisplus.enums.FieldFill;
-import com.baomidou.mybatisplus.enums.FieldStrategy;
-import com.baomidou.mybatisplus.test.h2.entity.SuperEntity;
-
-import lombok.Data;
-import lombok.experimental.Accessors;
-
-/**
- * <p>
- * 字段忽略 测试实体
- * </p>
- *
- * @author yuxiaobin
- * @date 2017/6/28
- */
-@Data
-@Accessors(chain = true)
-@TableName("h2user")
-public class H2UserFill extends SuperEntity {
-
-    /* 测试忽略验证 */
-    private String name;
-
-    private Integer age;
-
-    /*BigDecimal 测试*/
-    private BigDecimal price;
-
-    /* 测试下划线字段命名类型, 字段填充 */
-    @TableField(value = "test_type", fill = FieldFill.UPDATE)
-    private Integer testType;
-
-    @TableField(value = "desc", fill = FieldFill.INSERT)
-    private String desc;
-
-    @Version
-    private Integer version;
-}

+ 18 - 0
src/test/java/com/baomidou/mybatisplus/test/mysql/URPTest.java

@@ -15,7 +15,10 @@
  */
 package com.baomidou.mybatisplus.test.mysql;
 
+import java.util.List;
+
 import org.apache.ibatis.session.SqlSession;
+import org.junit.Assert;
 import org.junit.Test;
 
 import com.baomidou.mybatisplus.mapper.EntityWrapper;
@@ -37,6 +40,21 @@ import com.baomidou.mybatisplus.toolkit.IdWorker;
  */
 public class URPTest extends CrudTest {
 
+    @Test
+    public void crossResultMapTest() {
+        // 加载配置文件
+        SqlSession session = this.sqlSessionFactory().openSession();
+        RoleMapper roleMapper = session.getMapper(RoleMapper.class);
+        Role role = new Role();
+        role.setName("K 神");
+        role.setDescription("无敌战神 K");
+        role.setSort(2);
+        roleMapper.insert(role);
+        UserMapper userMapper = session.getMapper(UserMapper.class);
+        List<Role> roles = userMapper.selectRoleList();
+        Assert.assertTrue(roles.size() >= 1);
+    }
+
     @Test
     public void urpTest() {
         // 加载配置文件

+ 3 - 0
src/test/java/com/baomidou/mybatisplus/test/mysql/mapper/UserMapper.java

@@ -22,6 +22,7 @@ import org.apache.ibatis.annotations.Param;
 import org.apache.ibatis.session.RowBounds;
 
 import com.baomidou.mybatisplus.test.mysql.MyBaseMapper;
+import com.baomidou.mybatisplus.test.mysql.entity.Role;
 import com.baomidou.mybatisplus.test.mysql.entity.User;
 
 /**
@@ -68,4 +69,6 @@ public interface UserMapper extends MyBaseMapper<User> {
      */
     List<User> forSelect(RowBounds pagination, @Param("ids") List<String> ids);
 
+    // 测试跨 xml resultMap
+    List<Role> selectRoleList();
 }

+ 4 - 1
src/test/resources/mysql/RoleMapper.xml

@@ -4,5 +4,8 @@
 
 	<resultMap id="RoleMap" type="Role" autoMapping="true">
 		<id property="id" column="id" />
+		<id property="name" column="name" />
+		<id property="sort" column="sort" />
+		<id property="description" column="description" />
 	</resultMap>
-</mapper>
+</mapper>

+ 6 - 1
src/test/resources/mysql/UserMapper.xml

@@ -41,4 +41,9 @@
         <!-- 级联查询 -->
         <association column="role" property="role" select="com.baomidou.mybatisplus.test.mysql.mapper.RoleMapper.selectById"/>
     </resultMap>
-</mapper>
+
+    <!-- 测试 resultMap 结果集注入【 注意,实体需要注解 !! 】 -->
+    <select id="selectRoleList" resultMap="com.baomidou.mybatisplus.test.mysql.mapper.RoleMapper.RoleMap">
+      SELECT * FROM role
+    </select>
+</mapper>

+ 7 - 0
src/test/resources/mysql/mysql.sql

@@ -27,6 +27,13 @@ CREATE TABLE `role` (
   PRIMARY KEY (`id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
+-- ----------------------------
+--  Records of `role`
+-- ----------------------------
+BEGIN;
+INSERT INTO `role` VALUES ('1', '1', '1', '1');
+COMMIT;
+
 -- ----------------------------
 --  Table structure for `test`
 -- ----------------------------