软件编程
位置:首页>> 软件编程>> java编程>> 关于mybatis resulttype 返回值异常的问题

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

作者:光滑的秃头  发布时间:2021-08-09 20:26:19 

标签:mybatis,resulttype,返回值

mybatis resulttype 返回值异常

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

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

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

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

处理方式1:

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

处理方式2:

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


<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


<?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>

<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

注解方式:


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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com