好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

关于mybatis resulttype 返回值异常的问题

mybatis resulttype 返回值异常

在使用mybatis时。resulttype返回自定义的类时,可能返回的类中字段数据存在缺失。

例如:resulttype = "student" 但是当中有些字段为空

原因是因为数据库字段和实体类字段不对应导致的。 mybatis底层 查询数据返回会更据数据库的字段和实体类的字段进行匹配,不区分大小写。但是字段不一样就无法传递值

例如:数据库字段为:s_name 实体类字段为 name

处理方式1:

在查询时添加别名 select s_name as name from student 别名对于实体类当中的字段。

处理方式2:

返回一个resultMap map配置当中指定数据库中的列和实体类的类进行对应

?

1

< id column = "s_name" jdbcType = "VARCHAR" property = "name" />

mybatis resultType="map"的常见问题

在配置数据源的配置文件中,配置Mybatis的SqlSessionFactoryBean

一、map的key值 与select的字段顺序的不一致问题

解决方法:

resultType="map" 修改为 resultType="java.util.LinkedHashMap"

二、值为null的返回map中没相应的key

解决方法:

1.查询字段使用ifnull函数(可空字段较多时,不推荐)

2.修改mybatis配置

springmvc:

创建mybatis-config.xml

?

1

2

3

4

5

6

7

8

9

<? xml version = "1.0" encoding = "UTF-8" ?>

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

< configuration >

     < settings >

         <!-- 当返回数据类型为map,设置callSettersOnNulls会把值为null的key也返回 -->

         < setting name = "callSettersOnNulls" value = "true" />

     </ settings >

</ configuration >

?

1

2

3

4

5

6

7

8

9

< bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" >

     < property name = "dataSource" ref = "dataSource" />

     < property name = "configLocation" value = "classpath:/META-INF/spring/mybatis-config.xml" />

     < property name = "mapperLocations" >

     < array >

       < value >classpath*:/com/xxx/mapper/*.xml</ value >

     </ array >

  </ property >

</ bean >

springboot:

配置文件:mybatis.configuration.call-setters-on-nulls=true

注解方式:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer; 

import org.springframework.context.annotation.Bean; 

import org.springframework.context.annotation.Configuration; 

  

/**

  * mybatis 注解版 

  *

  */

@Configuration

public class MybatisConfig { 

  

     @Bean

     public ConfigurationCustomizer configurationCustomizer() { 

         return new ConfigurationCustomizer() { 

  

             @Override

             public void customize(org.apache.ibatis.session.Configuration configuration) { 

                 configuration.setMapUnderscoreToCamelCase( true ); //设置驼峰命名规则

                 configuration.setCallSettersOnNulls( true );

             } 

         }; 

     } 

}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/ycf921244819/article/details/80487599

查看更多关于关于mybatis resulttype 返回值异常的问题的详细内容...

  阅读:30次