MyBatis使用细节

1. 错误:with a primitive return type (int).

原因:返回值类型为int,但是查询出来的结果有空值(null),无法转换成基本类型。包括char,long,short都有可能。

解决方式:1. select ifnull(value, 0) from xxx;结果为空时默认返回返回值0。2. 如果where 条件命中不上,select语句则不会执行(where语句比select先执行),返回值仍为null。此情况一是使用 select case when then语句。二是修改Mapper接口中的返回值类型,改用包装类(Integer,Short,Long等),并在业务逻辑中处理null值。

select

CASE

WHEN (select provinceID from kdmc_t_province where name =#{province})is null

THEN 0
ELSE (select provinceID from kdmc_t_province where name =#{province})
END;

2. resultType和resultMap区别

查询出来的结果集只有一行且一列,可以使用简单类型进行输出映射。通过resultType映射。

如果查询结果复杂,需要封装成bean,则适合使用resultMap,定义映射规则。

3. 动态传入表名,例如数据记录日表

先区分#{}和${}的却别,简略来讲${}单纯填充字段,不做预编译;#{}有预编译过程,可以防止SQL注入。(#{} 是编译好SQL语句再取值,${} 这是取值以后再去编译SQL语句)

那么,动态传入表名则需要使用${}方式,例如select * from ${prefix}ACT_HI_PROCINST where PROC_INST_ID_ = #{processInstanceId},另外SQL语句配置为statementType="STATEMENT",即不进行预编译。

4. 多参数传递

单个参数配置文件映射时能自动识别,多参数则需要指定参数,一是通过Map传递,二是封装成bean,三是在接口通过注解标明。例如:

Integer getAccountPermissionValue(@Param("publicId") long publicId,
                                  @Param("prvCode") String prvCode) throws Exception;

 

4. 随机数生成

private String getFixLenthString(int strLength) {
        Random rm = new Random();
        // 获得随机数
        double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
        // 将获得的获得随机数转化为字符串
        String fixLenthString = String.valueOf(pross);
        // 返回固定的长度的随机数
        return fixLenthString.substring(2, strLength + 2);

5. insert返回主键id

insert语句配置useGeneratedKeys="true" keyProperty="id"即可,对于insert ignore into,insert into on duplicate key update不生效。另外param需以bean的方式传入,且接口通过bean.getId()获取主键id,sql返回结果只表示执行的状态。

6. resultMap示例

               autoMapping="true">
       
       
       
       
       
       
       
       
       
       
       
       
       
       

      
   

 

7. 批量插入示例


                           order= "AFTER">
            SELECT LAST_INSERT_ID()
       

        insert into redeem_code
        (bach_id, code, type, facevalue,create_user,create_time)
        values
       
            (
            #{reddemCode.batchId}, #{reddemCode.code},
            #{reddemCode.type},
            #{reddemCode.facevalue},
            #{reddemCode.createUser}, #{reddemCode.createTime}
            )
       

   

8. 文件操作 FileUtils(org.apache.commons.io)

 

你可能感兴趣的:(MyBatis使用细节)