我是靠谱客的博主 称心小伙,这篇文章主要介绍关于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); } }; } }

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

最后

以上就是称心小伙最近收集整理的关于关于mybatis resulttype 返回值异常的问题的全部内容,更多相关关于mybatis内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(235)

评论列表共有 0 条评论

立即
投稿
返回
顶部