好得很程序员自学网

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

基于mybatis查询结果映射不到对象的处理

mybatis查询结果映射不到对象

项目场景

使用mybatis+springboot 进行数据库的数据查询操作,一直拿不到返回结果。

问题描述

后端dao层(service层调mapper,方法的返回结果一直null)代码一直空指针,

APP 中接收数据代码:

?

1

2

3

4

//分类名称

        Integer blogCategoryId = blog.getBlogCategoryId();//这里有数据  22

        BlogCategory category = blogCategoryMapper.getCategoryById(blogCategoryId);//这里返回结果就一直 null

        blog.setBlogCategoryName(category.getCategoryName());//导致这里一调用方法就报空指针了。

原因分析

仔细检查了代码(debug),controller层+ service层没问题,那问题坑定再dao层。检查xml文件,但发现xml文件中查询方法的sql代码写的没问题:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

< select id= "getCategoryById" parameterType= "java.lang.Integer" resultType= "com.hhh.blog.entity.BlogCategory" >

        SELECT

            category_id,

            category_name,

            category_icon,

            category_rank,

            create_time,

            is_deleted

        FROM

            tb_blog_category

        WHERE

            category_id = #{blogCategoryId}

    </ select >

这里理论上没啥问题,但特么的就是数据库的数据映射不到对象中(实体类都是按照数据库数据对应的,只多不少)。

解决方案

?

1

resultType=[com.hhh.blog.entity.BlogCategory]

返回结果改成使用映射:

?

1

2

3

4

5

6

7

8

9

10

< select id= "getBlogCategoryPage" resultMap= "getBlogCategoryPageMap" >

 

   <resultMap id= "getBlogCategoryPageMap" type= "com.hhh.blog.entity.BlogCategory" >

         <id column = "category_id" jdbcType= "INTEGER" property= "categoryId" />

         <result column = "category_name" jdbcType= "VARCHAR" property= "categoryName" />

         <result column = "category_icon" jdbcType= "VARCHAR" property= "categoryIcon" />

         <result column = "category_rank" jdbcType= "INTEGER" property= "categoryRank" />

         <result column = "is_deleted" jdbcType= "TINYINT" property= "isDeleted" />

         <result column = "create_time" jdbcType= "DATE" property= "createTime" />

     </resultMap>

开启驼峰式命名匹配也可能解决上述问题。没试过。建议自己搞起来

mybatis结果映射遇到的问题

错误如下

org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.apache.ibatis.executor.ExecutorException: No constructor found in POJO.User matching [java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.String]
### The error may exist in Mapper/UserMapper
### The error may involve test.selectUserById
### The error occurred while handling results
### SQL: SELECT * FROM USER WHERE id=?
### Cause: org.apache.ibatis.executor.ExecutorException: No constructor found in POJO.User matching [java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.String]

解决方案

最后,将User构造器中int改为Integer即可、

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

原文链接:https://blog.csdn.net/qq_38341582/article/details/108814416

查看更多关于基于mybatis查询结果映射不到对象的处理的详细内容...

  阅读:24次