美文网首页从零开始学springboot
34. 从零开始学springboot-mybatis查询字段n

34. 从零开始学springboot-mybatis查询字段n

作者: 码哥说 | 来源:发表于2019-09-26 14:12 被阅读0次

前言

作者最近使用mybatis写sql查询,xml中查询某表记录,使用

    <!-- 查询列表 -->
    <select id="queryList" parameterType="com.mrcoder.query"
            resultType="map">
          select name, category  from product
    </select>

突然发现,返回的list,居然少了category这个字段,仔细一看,发现数据库中该值为null.

解决

当xml写sql时, resultType="map", mybatis默认会将值为null的字段不返回,这就导致了,你明明查询可能是5个字段,但是因为某些字段的值为null,最终返回的字段小于5个.

方案一(使用实体类作为resultType)

意思就是你定义一个实体类作为返回类型,这样null值也会填充实体对象,就不会出现这样情况.

方案二(修改配置)

  • 如果你是使用xml配置的mybatis,则加上以下配置
<?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>  
  <!--解决,查询返回结果含null没有对应字段值问题-->  
  <setting name="callSettersOnNulls" value="true"/>  
  </settings>  
</configuration> 
  • 如果你使用了配置类来配置mybatis的,则加上以下代码
    或者
    MybatisConfig.java:
configuration.setCallSettersOnNulls(true);

项目地址

https://github.com/MrCoderStack/SpringBootDemo

请关注我的订阅号

订阅号.png

相关文章

网友评论

    本文标题:34. 从零开始学springboot-mybatis查询字段n

    本文链接:https://www.haomeiwen.com/subject/mnqbuctx.html